codedude
codedude

Reputation: 6519

jQuery toggle click

Say I need an element to animate when clicked. To do this I just:

$('#header .icon').click(function() {
    $('#header form').animate({width:'195px'});
});

But how would I make it so that when I click the element again the opposite animate takes place? (e.g. animate to width: 0px; )

Upvotes: 2

Views: 26989

Answers (2)

Gásten
Gásten

Reputation: 133

I had a similar problem today, and none of the answers here solved it for me. My solution was to save states in order to have different things happen when the same element is clicked:

var estado="big";
$(".snacks").click(function() {
    if(estado == "big"){
        $("#men_snacks").animate({width:"183px", height:"45px"}, 1000);
        return estado="small";
    } else if(estado == "small") {
        $("#men_snacks").animate({width:"82%",height:"550px"},1000);
        return estado="big";
    }
});

Upvotes: 6

Nick Craver
Nick Craver

Reputation: 630399

You can use .toggle() like this:

$('#header .icon').toggle(function() {
  $('#header form').animate({width:'195px'});
}, function() {
  $('#header form').animate({width:'0px'});
});

If it was initially out you could toggle it's width like this:

$('#header .icon').click(function() {
  $('#header form').animate({width:'toggle'});
});

Upvotes: 13

Related Questions