Get css top value as number not as string?


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



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:

  Bla text bla this takes op vertical space....
  <div id='elem'>bla</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?

Moving css position using increment

It's not correct. You gave to use something like this

    top: parseInt(ball.css('top')) + movement.y + 'px',
    left: parseInt(ball.css('left')) + movement.x + 'px'

Get the computed style properties for the first element in the set of matched elements.

As you can see on the documentation website, jQuery.css will give us the computed value, meaning that we don't get 15 if the left value is 15px, for example. For that, we have to use parseInt. Check this answer for more nice usages of parseInt. So this should the its job, but as someone answered on that post, we can create a jQuery plugin to make it look nicer:

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

    top: ball.cssNumber('top') + movement.y + 'px',
    left: ball.cssNumber('left') + movement.x + 'px'

I have also created a working example for you.