2

How can I increase css values with jquery?

I want to increase values such as top and left, this is what i tried but does not work:

var left = 5;
$(.object).css("left" + 5);

the thing is that i need the value to be an integer rather than a string like "5px". I need 5 so that i can change it with numerical expressions.

3
  • 1
    duplicate of: stackoverflow.com/questions/6567114/… Commented May 18, 2012 at 22:56
  • thank you yankee, this was useful Commented May 18, 2012 at 23:28
  • 2
    $(object).css( "left", "+=5" ); Commented Mar 29, 2014 at 5:39

3 Answers 3

14

From .css() documentation:

As of jQuery 1.6, .css() accepts relative values similar to .animate(). Relative values are a string starting with += or -= to increment or decrement the current value. For example, if an element's padding-left was 10px, .css( "padding-left", "+=15" ) would result in a total padding-left of 25px.

So, you can increment left with your js variable with:

var left = 5;
$(object).css('left', '+=' + left);
Sign up to request clarification or add additional context in comments.

Comments

2

Yankee is right:

var left = parseInt($(object).css("left")); 

$(object).css('left', left+5);

1 Comment

How to stop increment this through jquery
-1
var left = 5;

$(object).css('left', left+=5);

3 Comments

That would always set the style to 10 (5 + 5), regardless of the previous value.
The sample code is so far from working, so I don't think that basing an answer on it is wise...
I tried the += method before, but it seems to interfere with other code, while yankee's suggestion of the duplicate was correct. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.