JQuery animate () to move a div to the right, then left, by clicking

I am trying to get a div to slide right and then back left. I currently have this code, but it slides to the right, and then immediately goes back without a second click. I also tried to implement the switch, but ended up breaking the script. I feel so close, but I can’t nail him.

$(function(){ $("#click").click(function(){ $("#click").animate({left:'+=100px'}, 'fast'); }); $("#click").click(function() { $("#click").animate({left:'0'}, 'fast'); }); }); 
+4
source share
4 answers

jsBin demo

 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'); }); 
+7
source

This is because according to the first event, the Div is actually moving 100 pixels to the right. But you have identified two right click events. Thus, the event is fired twice for each click.

So, your div moves 100px according to the first function, then the second function starts right away and it returns.

You can verify this by setting a warning. You can see two warnings even for one click ..

0
source

You need to determine (either using the left offset value or the variable) where the div is currently located, and accordingly move it in the right direction (if it remains, move it to the right and vice versa). So basically this is an if clause within a single click function.

0
source

It is best to queue two effects: .queue and .dequeue

You can see some examples and specifications here: http://api.jquery.com/queue/

0
source

Source: https://habr.com/ru/post/1432547/


All Articles