[javascript] Padding or margin value in pixels as integer using jQuery

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

This question is related to javascript jquery css

The answer is


The parseInt function has a "radix" parameter which defines the numeral system used on the conversion, so calling parseInt(jQuery('#something').css('margin-left'), 10); returns the left margin as an Integer.

This is what JSizes use.


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

var that = $("#myId");
alert(that.outerHeight(true) - that.innerHeight());

Don't use string.replace("px", ""));

Use parseInt or parseFloat!


You can just grab them as with any 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");

EDIT: If you need just the pixel value, use parseInt(val, 10):

parseInt($("#mybox").css("padding-right", "20px"), 10);

Parse int

parseInt(canvas.css("margin-left")); 

returns 0 for 0px


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

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

The result is 10px.

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

parseInt($("a").css("margin-top"))

I probably use github.com/bramstein/jsizes jquery plugin for paddings and margins in very comfortable way, Thanks...


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

Not to necro but I made this which can determine pixels based on a variety of values:

$.fn.extend({
  pixels: function (property, base) {
    var value = $(this).css(property);
    var original = value;
    var outer = property.indexOf('left') != -1 || property.indexOf('right') != -1 
      ? $(this).parent().outerWidth()
      : $(this).parent().outerHeight();

    // EM Conversion Factor
    base = base || 16;

    if (value == 'auto' || value == 'inherit') 
        return outer || 0;

    value = value.replace('rem', '');
    value = value.replace('em', '');

    if (value !== original) {
       value = parseFloat(value);
       return value ? base * value : 0;
    }

    value = value.replace('pt', '');

    if (value !== original) {
       value = parseFloat(value);
       return value ? value * 1.333333 : 0; // 1pt = 1.333px
    }

    value = value.replace('%', '');

    if (value !== original) {
      value = parseFloat(value);
      return value ? (outer * value / 100) : 0;
    }

    value = value.replace('px', '');
    return parseFloat(value) || 0;
  }
});

This way, we take into account for sizing, and auto / inherit.


This simple function will do it:

$.fn.pixels = function(property) {
    return parseInt(this.css(property).slice(0,-2));
};

Usage:

var padding = $('#myId').pixels('paddingTop');

Shamelessly adopted from Quickredfox.

jQuersy.fn.cssNum = function(){
    return parseInt(jQuery.fn.css.apply(this, arguments), 10);
};

update

Changed to parseInt(val, 10) since it is faster than parseFloat.

http://jsperf.com/number-vs-plus-vs-toint-vs-tofloat/20


PLEASE don't go loading another library just to do something that's already natively available!

jQuery's .css() converts %'s and em's to their pixel equivalent to begin with, and parseInt() will remove the 'px' from the end of the returned string and convert it to an integer:

http://jsfiddle.net/BXnXJ/

$(document).ready(function () {
    var $h1 = $('h1');
    console.log($h1);
    $h1.after($('<div>Padding-top: ' + parseInt($h1.css('padding-top')) + '</div>'));
    $h1.after($('<div>Margin-top: ' + parseInt($h1.css('margin-top')) + '</div>'));
});

Here's how you can get the surrounding dimentions:

var elem = $('#myId');

var marginTopBottom  = elem.outerHeight(true) - elem.outerHeight();
var marginLeftRight  = elem.outerWidth(true)  - elem.outerWidth();

var borderTopBottom  = elem.outerHeight() - elem.innerHeight();
var borderLeftRight  = elem.outerWidth()  - elem.innerWidth();

var paddingTopBottom  = elem.innerHeight() - elem.height();
var paddingLeftRight  = elem.innerWidth()  - elem.width();

Pay attention that each variable, paddingTopBottom for example, contains the sum of the margins on the both sides of the element; i.e., paddingTopBottom == paddingTop + paddingBottom. I wonder if there is a way to get them separately. Of course, if they are equal you can divide by 2 :)


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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width