Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get css top value as number not as string?

In jQuery you can get the top position relative to the parent as a number, but you can not get the css top value as a number if it was set in px.
Say I have the following:

#elem{
  position:relative;
  top:10px;
 }
<div>
  Bla text bla this takes op vertical space....
  <div id='elem'>bla</div>
</div>
$('#elem').position().top; //Returns the number (10+(the vertical space took by the text))
$('#elem').css('top'); //Returns the string '10px'

But I want to have the css top property as the number 10.
How would one achieve this?

like image 747
Pim Jager Avatar asked Dec 27 '08 17:12

Pim Jager


People also ask

How do you get top in CSS?

You can use the parseInt() function to convert the string to a number, e.g: parseInt($('#elem'). css('top'));

What is top attribute in CSS?

The top property affects the vertical position of a positioned element. This property has no effect on non-positioned elements. If position: absolute; or position: fixed; - the top property sets the top edge of an element to a unit above/below the top edge of its nearest positioned ancestor.

What is top value in CSS?

The top property in CSS is used to describe the top position of an element. The top property varies with the position of the element. If the position value is fixed or absolute, the element adjusts its top edge with respect to the top edge of its parent element or the block that holds it.


3 Answers

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

like image 136
M4N Avatar answered Nov 07 '22 22:11

M4N


A jQuery plugin based on M4N's answer

jQuery.fn.cssNumber = function(prop){
    var v = parseInt(this.css(prop),10);
    return isNaN(v) ? 0 : v;
};

So then you just use this method to get number values

$("#logo").cssNumber("top")
like image 44
Ivan Castellanos Avatar answered Nov 07 '22 21:11

Ivan Castellanos


A slightly more practical/efficient plugin based on Ivan Castellanos' answer (which was based on M4N's answer). Using || 0 will convert Nan to 0 without the testing step.

I've also provided float and int variations to suit the intended use:

jQuery.fn.cssInt = function (prop) {
    return parseInt(this.css(prop), 10) || 0;
};

jQuery.fn.cssFloat = function (prop) {
    return parseFloat(this.css(prop)) || 0;
};

Usage:

$('#elem').cssInt('top');    // e.g. returns 123 as an int
$('#elem').cssFloat('top');  // e.g. Returns 123.45 as a float

Test fiddle on http://jsfiddle.net/TrueBlueAussie/E5LTu/

like image 29
Gone Coding Avatar answered Nov 07 '22 22:11

Gone Coding