HOW TO USE THE TOGGLE FUNCTION WITH CLICK FUNCTION?

Jayden Bell

Total Post:110

Points:774
Posted by  Jayden Bell
JQuery 
 1545  View(s)
Ratings:
Rate this:
Hi Expert,

I like to create a animate when user click on a button.There are two animate function I like to do on click so I thought to use toggle function which swap between two function.

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

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

Here slider is the div which animates.

How to do the animate functions alternatively every time when user click a button?

Thanks in advance. 
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: How to use the toggle function with click function?

    Hi,


    You can try as following

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

    You can try as following

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

    I hope it helpful for you.

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!