sun
sun

Reputation: 1668

How to use the toggle function with click function?

I would like to create an animation when the user clicks on a button. There are two animate functions I want to do on click so I thought I would use the toggle function which swap between the two functions.

Now the problem is if I use the toggle function it is doing the two animate functions without click and also the button disappears.

$('#button').toggle(
    function() {
        $('#slider').stop().animate({"margin-right": '0'});
    },
    function() {
        $('#slider').stop().animate({"margin-right": '50'});
    }
);

How do I do the animate functions alternatively every time when the user clicks a button?

Upvotes: 0

Views: 108

Answers (2)

Rohan Kumar
Rohan Kumar

Reputation: 40639

Try this,

$('#button').on('click',function(){
   var mr=parseInt($('#slider').css('margin-right').replace('px',''))==0 ? 50 : 0;
   $('#slider').stop().animate({"margin-right": mr});
});

Alernatively,

var mr=0;
$('#button').on('click',function(){
    $('#slider').stop().animate({"margin-right": mr});
    mr=(mr==0) ? 50 : 0;
});

Upvotes: 0

Alnitak
Alnitak

Reputation: 339786

The .toggle(fn1, fn2) function has been deprecated.

The best alternative is to use a function that maintains a state variable to indicate whether it's an "even" click or an "odd" click.

In the example below I'm using an "immediately invoked function expression" to wrap that state variable in a closure (so that it's not global). Instead of an odd/even flag I'm actually using the expression target = 50 - target to flip the target coordinate alternately between 0 and 50 on each click.

Polling the current position of the element will not work correctly because it'll miss button clicks that happen mid-animation.

(function() {   // closure to hold state variable
    var target = 0;
    $('#button').on('click', function() {
        $('#slider').stop().animate({'margin-right': target});
        target = 50 - target;
     });
})();

See http://jsfiddle.net/alnitak/5daYu/

Upvotes: 2

Related Questions