4

I have this <div>:

<div class="ball" style="top: 1px;"></div>

The top property is set using jQuery function .css like so:

$( ".ball" ).css( { top : var_top } );

However, when I try to increment it using this syntax, it doesn't work:

$( ".ball" ).css( { top : "+=" + var_top } );

I even tried it in Firebug's console like this:

$( ".ball" ).css( { top : "+=7px" } );
$( ".ball" ).css( { top : "+=7" } );

but neither of these work either.

2
  • Are you using jQuery 1.6 or better? Commented May 24, 2012 at 14:24
  • @RobLowe I'm using the latest jQuery Commented May 24, 2012 at 14:54

2 Answers 2

3

you could try this

$( ".ball" ).css({ top : "+=" + var_top + 'px'});

NOTE: If .ball has position:absolute then, its parent need to have position:relative;

And it seems your code is also working

Sign up to request clarification or add additional context in comments.

1 Comment

It's parent has a relative position of course but, I'm trying to make a classical Pong game in javascript/jQuery and when the balls gets to the top it won't increment it's property. I guess it's a problem in my code but then, why isn't it working at least in the console?
0

I think you have to retrieve the old value, increment it and than reassign it:

var topPosition = $( ".ball" ).css('top');
topPosition += increment;
$( ".ball" ).css('top', topPosition);

3 Comments

You don't need to do that. You can use += and -= with jQuery css.
Is this a new feature? I have never encountered it before!
The feature is new in jQuery 1.6

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.