0

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?

Léo Léopold Hertz 준영
  • 134,464
  • 179
  • 445
  • 697
MayThrow
  • 2,159
  • 4
  • 24
  • 38

4 Answers4

4

Keep a flag outside of the method:

var open = false;

jQuery('.button').click(function() {
    open = !open;

    if(open) {
        jQuery('.div1').animate({width: '100%'});
        jQuery('.div2').animate({width: '100%'});
    } else {
        jQuery('.div1').animate({width: '0%'});
        jQuery('.div2').animate({width: '50%'}); // Or whatever else you want to lower it to
    }
});
Ry-
  • 218,210
  • 55
  • 464
  • 476
2

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%'});
});
Jon
  • 428,835
  • 81
  • 738
  • 806
0

Try using a toggleClass instead and using css to handle the different styles.

Merlin Mason
  • 1,607
  • 2
  • 12
  • 14
-1

Use variable and update it after each click, example:

`
var $toggle = 0;
$('.button').click(function(){
    if($toggle == 0){
        $('.div1').animate({width: '50%'});
        $toggle = 1;
    }else{
        $('.div1').animate({width: '100%'});
        $toggle = 0;
    };

});
`