JQuery: How can I use delegation delegation with classes added to nested divs?

I am trying to encode this poem using nested divs and basic jQuery. My idea was to start with one div of the class .activethat has display: block, and all the rest divare children of the first divc display: none. Now, when you click on the first one div, it removes the class .activefrom itself (adds a class to itself .static, which at the moment just changes color) and adds .activeit to the child. In fact, the child divbecomes visible. Then you click on this child to open his child and so on until the end of the poem:

$(".active").click(function() {
  $(this).removeClass("active").addClass("static");
  $(this).children("div").addClass("active")
});

Only the first div class .activeexists in the DOM when loading the script. The click works on the first div and is ignored on the following, as in this fiddle: https://jsfiddle.net/4ygfrtgb/1/

I tried event delegation as follows:

$("div").on("click", ".active", function() {
  $(this).removeClass("active").addClass("static");
  $(this).children("div").addClass("active");
});

However, even the first divdoes not respond to a click. I understand that delegation is working on children of the elements, and I'm trying to call a class on the same element.

So, is there a way to target elements to a class that is added after loading the DOM?

Thank you.

+6
source share
1 answer

You are not properly delegating events ... Read more about this here .

. .

, div ( , body).

$("body").on("click", "div.active", function() {
  $(this).removeClass("active").addClass("static");
  $(this).children("div").addClass("active");
});

JSFiddle, , : https://jsfiddle.net/4ygfrtgb/2/.

+3

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


All Articles