Sam Friday Welch
Sam Friday Welch

Reputation: 255

How to toggle an animation upon clicking a button

I have the following j-query code (using the jquery plugin ajax/libs/jquery/1.10.1) to move a div element to the left upon clicking on a separate div element:

<script>
$(document).ready(function(){
$("#tab_box3").click(function(){
$.fx.speeds._default = 800;             
$("#tab3").animate({left:"+=97%"});
});  
});
</script>

What I want to happen is when the #tab_box3 div is clicked on a second time, the #tab3 div moves back to where it originally started.

I tried the following, using Toggle, but it does not seem to have worked:

<script>
$(document).ready(function(){
$("#tab_box3").click(function(){
$.fx.speeds._default = 800;             
$("#tab3").animateToggle({left:"+=97%"});
});  
});
</script>

Can anyone offer advice please?

Upvotes: 2

Views: 509

Answers (2)

Paul Rad
Paul Rad

Reputation: 4882

You must doing something like this :

    $(document).ready(function(){
    $("#tab_box3").click(function(e){
        var element = $(this),
            clicked = parseInt(element.data('clicked')) || 0;

        element.data('clicked', clicked + 1);
        $("#tab3").stop();
        if (clicked % 2 == 0)
        {
            $("#tab3").animate({left:"+=97%"}, 800);
        }
        else
        {
            $("#tab3").animate({left:"-=97%"}, 800);
        }
        e.preventDefault();
    });  
});

An example here : http://jsfiddle.net/Q5HDu/

Upvotes: 6

Explosion Pills
Explosion Pills

Reputation: 191749

You will have to use -=97% to offset the previous animation change.

var $tab3 = $("#tab3");
if ($tab3.data("animated")) {
    $tab3.animate({left: "-=97%").data("animated", false);
}
else {
    $tab3.animate({left: "+=97%").data("animated", true);
}

Upvotes: 0

Related Questions