0

EDIT: for a general solution, this worked for me. Event binding on dynamically created elements?

So I have a interface that kind of looks like this:

default

User can toggle to show or hide the sublists. I used jquery to select the toggle buttons for them to work:

$(".dropdownBtn").click(function(){
  //rotate the button
  $(this).parent().toggleClass("caret-down");
  //hide the sublist
  $(this).closest("li").find(".active").toggleClass("nested");
})

They can also add new sub_elements to each element. For example, like this:

updat

$(".fa-plus-square").click(function(){
//if there's no new list, create a new unordered list
  if ($(this).closest("li").find("ul").length == 0){
    $(this).parents("li").append(newUL);
    //and add a toggle button
    $(this).parent().prepend(toggleBtn);
  }
  //add the element
  $(this).closest("li").find("ul").append("<li>newElement</li>")
})

But then the newly added toggle button under element 3 wouldn't respond. I believe that I need to "bind" the newly added button. But I'm not sure what's the best practice to do so.

Samson Liu
  • 460
  • 4
  • 20
  • Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – matthias_h Apr 26 '20 at 12:17
  • @matthias_h Thanks for the comment! I tried the `($document).on(event, selector, data)` method. It did record the events triggered by the newly added element, but I also lose track on which button was clicked.. – Samson Liu Apr 26 '20 at 12:34
  • Are you losing track of the button inside the on() event? Inside this event, the button which was clicked can be referred to as $(this). – matthias_h Apr 26 '20 at 12:37
  • @matthias_h Ah. After a lot of logging I can only assume that `.toggleClass()` is bugged. Though I'm almost sure $(this) returns the same thing in both .on() and .click(). – Samson Liu Apr 26 '20 at 12:48
  • @matthias_h Sorry this might deserve its own question but I'm really confused. hasClass and removeClass doesn't work either. To be more specific, toggleClass, hasClass and such all work in `(selector).on(event, data)`, but do not in `(ancestor).on(event, selector, data)`. – Samson Liu Apr 26 '20 at 12:56
  • @matthias_h Actually nevermind. I'm so sorry for bothering but I think I figured it out. It has something to do with events happening at different depths of the DOM tree. I need two functions. I'll edit the question. – Samson Liu Apr 26 '20 at 13:04
  • If it's a different question now, I suggest it's better to make a new question out of it so people will notice it more easily. – matthias_h Apr 26 '20 at 13:11

0 Answers0