jqueryjquery-animatetogglejquery-1.7

Run different function on clicking again


I have this code

jQuery('.button').click(function() {
    jQuery('.div1').animate({width: 'toggle'});
    jQuery('.div2').animate({width: '100%'});
});

Works fine for once. But I want to bring back div2 on clicking again. toggle would've worked but the problem is, I don't want to hide div2 but just lower its width with animation.

What would be the correct code to do that?


Solution

  • Updated solution

    Since .toggle was deprecated in jQuery 1.8 and removed in 1.9, the go-to solution would now involve manually keeping track of clicks in order to decide what to do. A generalized drop-in replacement for toggle would be:

    var handlers = [
        // on first click:
        function() {
            jQuery('.div1').animate({width: 'toggle'});
            jQuery('.div2').animate({width: '50%'});
        },
        // on second click:
        function() {
            jQuery('.div1').animate({width: 'toggle'});
            jQuery('.div2').animate({width: '100%'});
        }
        // ...as many more as you want here
    ];
    
    var counter = 0;
    $(".button").click(function() {
        // call the appropriate function preserving this and any arguments
        handlers[counter++].apply(this, Array.prototype.slice.apply(arguments));
        // "wrap around" when all handlers have been called
        counter %= handlers.length;
    });
    

    Original answer

    You can simply use .toggle:

    jQuery('.button').toggle(function() {
        jQuery('.div1').animate({width: 'toggle'});
        jQuery('.div2').animate({width: '50%'});
    }, function() {
        jQuery('.div1').animate({width: 'toggle'});
        jQuery('.div2').animate({width: '100%'});
    });
    

    On each click, this will toggle the visibility of .div1 completely and toggle the width of .div2 between 50% and 100%.

    If you don't want to show .div1 again after first hiding it, simply do

    jQuery('.button').toggle(function() {
        jQuery('.div1').animate({width: 'hide'});
        jQuery('.div2').animate({width: '50%'});
    }, function() {
        jQuery('.div2').animate({width: '100%'});
    });