Increasing padding-top CSS property in Javascript

I have CSS defined for div

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

      

In JS function, I would like to increase the value 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


source to share


2 answers


The property .style

can only read inline styles defined for an element. It cannot read styles defined in stylesheets.

Do 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 will look like this:



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

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

      

Literature:

+6


source


You have to use jquery for this sort of thing, as most other solutions won't be very cross-browser compatible and you will spend a few days pulling your hair on top of it.

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

      



See jquery.com for details.

+1


source







All Articles