clusterBuddy
clusterBuddy

Reputation: 1554

How to use JQuery.find() when DOM is dynamic

I have a cascading menu with the following flow;

```

$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

Answers (3)

user1751825
user1751825

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

Danijel
Danijel

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

Calvin Ellis
Calvin Ellis

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

Related Questions