Skip to content Skip to sidebar Skip to footer

Incrementing The Css Padding-top Property In Javascript

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

Solution 1:

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):

functiongetStyle(elem, name) {
    // J/S Pro Techniques p136if (elem.style[name]) {
        return elem.style[name];
    } elseif (elem.currentStyle) {
        return elem.currentStyle[name];
    }
    elseif (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 {
        returnnull;
    }
}

Then your code becomes:

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

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

References:

Solution 2:

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.

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

See jquery.com for more.

Post a Comment for "Incrementing The Css Padding-top Property In Javascript"