I have a div to show/hide on click and this div will load content from me.html via ajax load. I am adding a class class added to this a tag and then when I click again on a tag with added class, it should hide the div. But this doesn’t work.
$(function() {
$("#nav a").click(function() {
$(this).toggleClass('added');
if($(".o1").length <= 0) {
$("body").append('<div class="o1"></div>');
$(".o1").load("me.html").css("display","block");
}
$(".added").click(function() {
$(".o1").css("display","none");
})
});
});
Any ideas?
Try this. This will setup the object if it doesn’t exist. Then once it does it will toggle it if for future clicks.
Adding a
clickhandler to all.addedlinks with your code would create a problem, because in your code you have.This shows the timeline of what is happening. Hope you can follow. The numbers in brackets are events. The same number signifies they happen at the same time.
(1)
#nav ais clicked then#nav agets a class ofaddedthen.o1is added then any link withaddedclass gets a click event(2)
#nav ais clicked then#nav aremoves class ofaddedthen.o1already exists then any link withaddedclass gets a click event (but not this link, but it still has the previous click event, because it wasn’t dettached)(2)
.addedis also considered clicked at the same time as action above because it was attached during (1)(3)
#nav ais clicked then#nav agets a class ofaddedthen.o1already exists then any link withaddedclass gets a click event(3)
.addedis also considered clicked at the same time as action above because it was attached during (1)(4)
#nav ais clicked then#nav agets a class ofaddedthen.o1already exists then any link withaddedclass gets a click event(4)
.addedis also considered clicked at the same time as action above because it was attached during (1)(4)
.addedis also considered clicked at the same time as action above because it was attached during (3)etc …
The key thing to grasp is you are not detaching
clickevents, instead you are attaching more and more.