Hard worker
Hard worker

Reputation: 4046

How to add to an element's position

I would like to add to an element's position a dynamic amount e.g. 40px to the right.

This code below for example gets an element's right offset relative to the appropriate parent:

$('#example').css('right')

But it returns a string such as '12px', I want a method I can add numbers to.

As an analogue I am able to add a given amount to the width of an element as below:

$('#example').width($('#example').width()+355)

I would like to be able to do something similar to the position.

Thanks.

Upvotes: 0

Views: 49

Answers (2)

idrumgood
idrumgood

Reputation: 4924

$('#example').css('right' , '+=355');

The += will take care of that for you.

jQuery 1.6+

Upvotes: 4

jcolebrand
jcolebrand

Reputation: 16025

var val = parseInt($('#example').css('right'));

parseInt will read the first numbers it comes across until it comes to a non-number.

Here's an MDN article on the topic, where they go into more detail: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/parseInt

But what you want to know is that if you get a value, like '12px', using parseInt on that value will give you (in this case) 12.

If you passed in '123x123' you would get 123.

Passing in 'x123' would get NaN.

Upvotes: 1

Related Questions