1

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.

6
  • 1
    is button is inside or outside panel.? Commented Jan 24, 2013 at 8:56
  • Outside and after the panel. Commented Jan 24, 2013 at 8:57
  • paste little html code... Commented Jan 24, 2013 at 8:58
  • Which jQuery version you use? Commented Jan 24, 2013 at 8:59
  • its working nothing wrong. Commented Jan 24, 2013 at 8:59

2 Answers 2

5

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

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

could be what you are asking?

Sign up to request clarification or add additional context in comments.

3 Comments

Oh lordy, I didn't know this existed. This is precisely what I'm trying to accomplish. Thanks!
$("#panel").stop().slideToggle(500); will do better... See jsfiddle.net/kFdnF
@A.V thats what most want, but maybe Rafay want to quere up his slides :)
2

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/

3 Comments

@Liam that's where I was looking - the version the OP is trying to use is at api.jquery.com/toggle-event but it's deprecated in 1.8 and removed in 1.9
How very irresponsible of me; I should have checked the docs first. Oh well, it was a good function.
Yeah, just adding to give a little extra info to the OP

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.