Rafay
Rafay

Reputation: 24265

jQuery - Toggle between functions on click

Problem
I'm trying to toggle between two functions when a button is clicked using jQuery's .toggle() method, but the button itself goes away as soon as the DOM is ready.

Code

$(document).ready(function() {

    $("#panel").css({"height": "0%", "bottom": "0"});

/*
    var already_clicked = false;
    $("button").on("click", function() {
        if (already_clicked) {
            $("#panel").animate({"height": "0%"}, 500);
            already_clicked = false;
        } else {
            $("#panel").animate({"height": "100%"}, 500);
            already_clicked = true;
        }
    });
*/

    $("button").toggle(function() {
        $("#panel").animate({"height": "100%"}, 500);
    }, function() {
        $("#panel").animate({"height": "0%"}, 500);
    });

});

Markup

<body>
    <div id="panel"></div>
    <button>Click me</button>
</body>

Note: The solution in the comment block works as intended, but I'm not sure why .toggle() doesn't works.

Upvotes: 1

Views: 2200

Answers (2)

Alnitak
Alnitak

Reputation: 339786

If you are using jQuery 1.9 then .toggle doesn't work like that - the version that takes two functions as arguments was deprecated in 1.8 and removed in 1.9

See http://api.jquery.com/toggle-event/

Upvotes: 2

voigtan
voigtan

Reputation: 9031

Im not to use if this is what you want but .slideToggle:

$("button").click(function() {
    $("#panel").slideToggle(500);
});

could be what you are asking?

Upvotes: 5

Related Questions