views:

12276

answers:

7

jQuery has height() en width() functions that returns the height or width in pixels as integer...

How can I get a padding or margin value of an element in pixels and as integer using jQuery?

My first idea was to do the following:

var padding = parseInt(jQuery("myId").css("padding-top"));

But if padding is given in ems for example, how can I get the value in pixels?


Looking into the JSizes plugin suggested by Chris Pebble i realized that my own version was the right one :). jQuery returns always value in pixels, so just parsing it to integer was the solution.

Thanks to Chris Pebble and Ian Robinson

+10  A: 

You should be able to use CSS (http://docs.jquery.com/CSS/css#name). You may have to be more specific such as "padding-left" or "margin-top".

Example:

CSS

a, a:link, a:hover, a:visited, a:active {color:black;margin-top:10px;text-decoration: none;}

JS

alert($("a").css("margin-top"));

The result is 10px.

Update: If you want to get the "integer" value, you can do the following:

alert($("a").css("margin-top").replace("px", ""));
Ian Robinson
I need to get the value as integer not as string and in pixels...
masterik
I believe jQuery adds the "px" so we should be able to reliably expect its presence and remove it - see my edit above.
Ian Robinson
I haven't checked if the jQuery method actually returns the "px" suffix or not, however the `JSizes` plugin from the other answer (which I ended up using) returns an integer when the return value is passed into `ParseInt(...)`, just FYI.
Dan Herbert
+2  A: 

You can just grab them like any other CSS attribute:

alert($("#mybox").css("padding-right"));
alert($("#mybox").css("margin-bottom"));

You can set them with a second attribute in the css method:

$("#mybox").css("padding-right", "20px");
Robert Grant
+2  A: 

Compare outer and inner height/widths to get the total margin and padding:

var that = $("#myId");
alert(that.outerHeight(true) - that.innerHeight());
svinto
+4  A: 

There's a jQuery plugin called JSizes that does just this.

Chris Pebble
A: 

Maybe jQuery dimensions plugin somehow would be handy...

miceuz
A: 

You could also extend the jquery framework yourself with something like:

jQuery.fn.margin = function() {
var marginTop = this.outerHeight(true) - this.outerHeight();
var marginLeft = this.outerWidth(true) - this.outerWidth();

return {
    top: marginTop,
    left: marginLeft
}};

Thereby adding a function on your jquery objects called margin(), which returns a collection like the offset function.

fx.

$("#myObject").margin().top
cralexns
A: 

ok just to answer the original question:

you can get the padding as a usable integer like this:

var padding = parseInt($("myId").css("padding-top").replace("ems",""));

If you have defined another measurement like px just replace "ems" with "px". parseInt interprets the stringpart as a wrong value so its important to replace it with ... nothing.

EeKay