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%'});
});