3

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;
}

2 Answers 2

8

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:

Sign up to request clarification or add additional context in comments.

Comments

1

You should be using jquery to do this sort of thing, as most other solutions won't be very cross browser compatible and you'll spend days pulling your hair out over it.

function Dostuff()
{
    var currentPadding =  $('#myDiv').css('padding-top');
    $('#myDiv').css('padding-top', currentPadding + 1);
}

See jquery.com for more.

5 Comments

yeah but I think jQuery is the defacto and the best IMO.
try to avoid global vars (currentPadding) by using the var keyword to scope it
actually, this doesn't seem to be working for me. currentPadding + 1 is coming up with stuff like "25px1"
try var currentPadding = parseInt($('#myDiv').css('padding-top'));
Or, if padding can possibly be a floating point number due to using em's or something, use parseFloat()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.