Reputation: 153
I have a problem with jQuery and the toggleClass(). I want to create a div, which closes on clicking a button. The button changes and when I click again on this button the div will open again.
The problem is: When I click on the button the div closes and the class of the button changes - thats fine. But now when I click on the button with the new class - nothing happens.
Here is my code:
<div class="content">
<div class="contentclose"></div>
<p>Text here</p>
</div>
and the jQuery:
$( document ).ready(function() {
$(".contentclose").click(
function() {
$(".content").animate({
"height": "45px",
"width": "45px",
"padding": "0px"
}, 1000);
$(".content").children("p").animate({
"opacity": "0"
}, 1000);
$(".contentclose").toggleClass("contentclose contentopen");
}
);
$(".contentopen").click(
function() {
$(".content").animate({
"height": "400px",
"width": "200px",
"padding": "50px"
}, 1000);
$(".content").children("p").animate({
"opacity": "1"
}, 1000);
$(".contentopen").toggleClass("contentopen contentclose");
}
); });
I hope you can help me...
Upvotes: 3
Views: 4313
Reputation: 3063
When the document is ready, the DOM do not contain a class with name contentopen, so it is impossible to bind the contentopen click event.
Upvotes: 0
Reputation: 1075199
You're binding your event handlers to the elements that have those classes as of when your code doing the binding runs. That code isn't magically re-run to rebind things later.
You can use event delegation to get something similar to that magic, though. Change:
$(".contentclose").click(function...
to
$(document).on("click", ".contentclose", function...
and change
$(".contentopen").click(function...
to
$(document).on("click", ".contentopen", function...
(Ideally, use a container that's closer to the buttons than document
. Any common ancestor will do.)
What that does is bind click
to the ancestor element (document
in my example), but then trigger the relevant handler based on whether the click originated or passed through something matching the given selector when the event was bubbling.
So if a click reaches document
having bubbled from (or through) a .contentclose
button, the handler we've attached in that line is run. But if it bubbled from (or through) a .contentclose
button, the other handler is run. It's dynamically determined when the click occurs, instead of being statically determined when you hook up the handler.
Upvotes: 6