Skip to content
Advertisement

Issue with filtering on dynamically added elements

I have the following code to filter a UL list based on click on another UL.

I will append dynamically some more elements to the bs-glyphicons-list-sub list to be filtered and I need to modify my code for this.

JavaScript
JavaScript

The line I need to modify is the following:

JavaScript

where I need to include the elements that I appended after DOM ready. I know about delegated events, I know how to use .on(), what I don’t know is how to apply delegated events binding to the filter function here. The elements I click on are immutable so I don’t think that using .on() on the click event may lead to something useful.

Advertisement

Answer

What you are doing is: Add event handling to elements, which are available at the start ($('.show-fields').click()). DOM elements that are added later don’t trigger this event.

What you need to be doing is: Delegate the click event. By catching the event on the <ul> which is already there at startup and delegating the event handling to the <li> on which the event occurred, you also catch DOM elements inside the <ul> which are added later.

I also deleted the then branch of the if, because you can set the filter for tutti to the empty string and it will work automatically.

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement