The second .click () function does not work

The first .click function is used to add an element (div) to the container, and the second is used to remove it from the container. The container initially has no elements. Deleting a function by clicking on it does not work.

$(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 already exists before the page is loaded into the container. Any reasons? Is it because of the document.ready function? Solutions?

+6
source share
4 answers

This is because when you add a click handler for .class2 elements, you only add an event to elements that have this class at this particular point in time ; for example, no.

Instead, you need to use event delegation like this:

 $(document).on('click', '.class2', function () { alert('hi'); $(this).fadeOut(100); }); 

This will work because it associates an event with a document (which always exists) that listens for clicks on any .class2 elements using event delegation. Read the on() documentation for more information.

+14
source

use the delegate event handler for both classes (if you switch between them, or if you do not return to class1 , then the second is enough), because after changing the class elements are considered as dynamic.

 $("#container").on("click", ".class1", function(){ }); $("#container").on("click", ".class2", function(){ }); 

Here #container refers to the parent of this class, you may have something else.

+3
source

As you try to add code by clicking .class2 , it has not yet been created, as I understand it. try adding the click event after creating the .class2 element as follows:

 $(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); }); }); }); 
+1
source

Events cannot be superimposed on elements that do not exist when a function is developed. But you can create a wrapper element (div) around "class1" and "class2", for example:

 <div id="class1_wrapper"> <span class="class1"> </div> 

I used "span" for class 1 because I do not know what element it is. Then, instead of the click event, you can use "on ()":

  $("#class1_wrapper").on("click", ".class1", function () { //Code for adding element to the container and removing class1 from it and adding class2 }); 

this way, even if class1 does not exist (the same thing can be done for class 2), the click event will be fired

0
source

Source: https://habr.com/ru/post/918741/


All Articles