Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing the CSS padding-top property in Javascript

Tags:

javascript

css

I have a CSS defined for a div

#myDiv
{
  padding-top: 20px,
  padding-bottom: 30px
}

In a JS function, I would like to increment the value of padding-top by 10px

function DoStuff()
{
  var myDiv = document.getElementById('myDiv');
  //Increment by 10px. Which property to use and how? something like..
  //myDiv.style.paddingTop += 10px;
}
like image 406
Nick Avatar asked Sep 12 '26 10:09

Nick


1 Answers

The .style property can only read inline styles defined on an element. It cannot read styles defined in stylesheets.

You need a library to get the value, or use something like (from this question):

function getStyle(elem, name) {
    // J/S Pro Techniques p136
    if (elem.style[name]) {
        return elem.style[name];
    } else if (elem.currentStyle) {
        return elem.currentStyle[name];
    }
    else if (document.defaultView && document.defaultView.getComputedStyle) {
        name = name.replace(/([A-Z])/g, "-$1");
        name = name.toLowerCase();
        s = document.defaultView.getComputedStyle(elem, "");
        return s && s.getPropertyValue(name);
    } else {
        return null;
    }
}

Then your code becomes:

var element = document.getElementById('myDiv'),
    padding = getStyle(element, 'paddingTop'); // eg "10px"

element.style.paddingTop = parseInt(padding, 10) + 10 + 'px';

References:

  • .style and inline vs stylesheet styles
  • getStyle function
  • radix (2nd) parameter to parseInt
like image 66
Crescent Fresh Avatar answered Sep 14 '26 23:09

Crescent Fresh