What is jQuery css syntax for adding and subtracting by numeric values?

I am sure I have seen this before. That's how i remember him

$cnta.css({ top:'+=50' });

Needless to say, it does not work :-)

I know that I can parse the css value, process the result and put it back in css, but it takes twice as much code.


Thanks for answers!

+4
source share
1 answer

This works for .animate() :

 $cnta.animate({ top:'+=50' }, 0); 

For .css() you can pass a function that will make an addition for you:

$ cnta.css ('top', function (i, current) {return parseInt (current) + 50;});

 $cnta.css('top', function(i,current) { return (parseInt(current) + 50 || 50); });​ 

EDIT: Changed animation from 1 to 0 . As @Nick Craver noted, animation 0 will work.

EDIT: Got the best answer for .css() version. If top has not yet been provided with any value, then executing .parseInt(current) will return NaN . Updated to fix it.

+8
source

All Articles