chris_s
chris_s

Reputation: 1051

jQuery animate() to move div right, then left, on click

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

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

    $("#click").click(function() {
        $("#click").animate({left:'0'}, 'fast');
    });
});

Upvotes: 4

Views: 22230

Answers (4)

Roko C. Buljan
Roko C. Buljan

Reputation: 206565

jsBin demo

var c=0;
$("#click").click(function(){
    $(this).stop().animate({left: ++c%2*100 }, 'fast');
});

To explain the math behind this solution:
after every click the var c gets pre-incremented so basically after 10 clicks c will be == 10 and using modulus 10%2 = 0, and if you continue to click the math is:
11%2 =1
12%2 =0
13%2 =1
14%2 =0 ... and so on
if you multiply 1 by 100 = 100 (the 100px needed) and every even (0*100) will result in our 0px!


or like this:

var dir = 0;
$("#click").click(function(){
     dir = dir===0 ? 100 : 0;
     $(this).stop().animate({left: dir }, 'fast');
});

Upvotes: 7

steve-er-rino
steve-er-rino

Reputation: 403

It might be best to queue the two effects use .queue and .dequeue

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

Upvotes: 0

Shomz
Shomz

Reputation: 37711

You need to determine (either by the left offset value or by a variable) where the div is currently and according to that move it in the right direction (if it's left, move it right, and vice versa). So, basically an if-clause within a single click function handles this.

Upvotes: 0

Sushanth --
Sushanth --

Reputation: 55750

That is because according to the first event the Div actually moves right by 100px. But you defined two click events right . So the event is called twice for each click.

So your div moves 100px accoding to the first function, then immediately the second function is fired and it moves back.

You can check this by placing an alert.. You can see two alerts even for a single click..

Upvotes: 0

Related Questions