var c=0; $("#click").click(function(){ $(this).stop().animate({left: ++c%2*100 }, 'fast'); });
To explain the math behind this solution:
after each click, var c gets pre-incremented, so basically after 10 clicks c will be == 10 and using the module 10%2 = 0 , and if you continue to click on the math:
11% 2 =1
12% 2 =0
13% 2 =1
14% 2 =0 ... and so on
if you multiply 1 by 100 = 100 (100 pixels are required), and every even (0 * 100) will lead to our 0px!
or like this:
var dir = 0; $("#click").click(function(){ dir = dir===0 ? 100 : 0; $(this).stop().animate({left: dir }, 'fast'); });
source share