The first .click function is used to add an element(div) in a container and the second one is used to remove it from the container. The container initially has no elements. The removing of the function by clicking on it is not working
$(document).ready(function(){
$(".class1").click(function(){
//Code for adding element to the container and
// removing class1 from it and adding class2
});
$(".class2").click(function(){
alert("hi"); //Even the alert is not displayed
$(this).fadeOut(100);
});
});
However, it works if the element is already there before the page loads in the container.
Any reasons why? Is it because of document.ready function? Solutions?
That’s because when you’re adding the click handler for
.class2elements, you’re only adding the event to elements which have that class at that specific moment in time; e.g none.Instead, you need to use event delegation like so;
This will work as it binds an event to
document(which always exists), which listens for clicks on any.class2elements using event delegation. For more info, read theon()documentation.