Reputation: 1554
I have a cascading menu with the following flow;
li
elementscreates and updates menu-3 li
elements
etc..
```
$firstMenu = $('.prime-menu');
$secondtMenu = $('.second-menu');
$thirdMenu = $('.third-menu');
```
As i'm traversing through different elems. within each menu, using find()
comes as a blessing, the issue is that the script loads when no menu other than the first menu is created so $secondtMenu.find('.item-year').click(function (clickEvent) {})
is 0 length.
What are my options in JQuery to make my find()
functions work on elements that are not loaded yet in the DOM?
I thought of creating an event listener, but I think there are more terse approaches than that.
Upvotes: 1
Views: 437
Reputation: 4309
Bind the click handler to the menu parent, not the actual menu items.
Something like this might work...
$("#menuparent").on("click",".item-year",function(event) {
var clicked_element = event.currentTarget;
});
Doing it this way, even if the element with class .item-year is added to the dom after the click event is bound, it will still register the click.
Upvotes: 0
Reputation: 1185
You should use delegates when dealing with dynamic HTML. For instance, use an outer element like document
or body
to "start" your finds.
$(document).find(".prime-menu");
EDIT: Find and event delegation The solution was to use find with event delegation. Example event.
$(document).find(".prime-menu").on('mouseenter', '.track-table tbody tr', function(){ });
Upvotes: 1
Reputation: 297
You state that when you click on an item from menu-1 it creates and updates menu-2 li elements. In this function is where you should do your event binding. The DOMElement will exist in js before being added to the dom, and that is where your bindings should be set.
If you need help share this code with us I'm sure myself or someone will be able to help you sort it out.
Upvotes: 0