views:

58

answers:

2

I have a site with a few containers that need to load content dynamically via AJAX.

Most of the links inside of the containers actually load new data in that same container.

I.E: $("#navmenu_item1").click(function() { $("#navmenu").load(blah); });

When I click on a link, lets say "logout," and the menu reloads with the updated login status, none of the links now work because I would need to add a new .click into the callback code.

Now with repeated clicks and AJAX requests I am not sure how to move forward from here, as I am sure nested callbacks are not optimal.

What would be the best way to do this?

Do I include the .click event inside the actual AJAX file being pulled from the server, instead of within index.php? Or can I somehow reload the DOM?

Thanks for the help!

+1  A: 

You're looking for the .live function, which will handle an event for all elements that match a selector, no matter when they were created.

SLaks
SLaks is correct also and/or delegate function which has the same characteristic but can also be chained.
XGreen
+1  A: 

Since you're reloading a particular element, you can store the event listener there using .delegate() like this:

$("#navmenu").delegate("#navmenu_item1", "click", function() {
  $("#navmenu").load(blah);
});

This works by listening for the click to bubble up to the #navmenu element and executing any handlers that match the selector. The .delegate() format is .delegate(selector, event, handler).

Since you're loading inside #navmenu, the event handlers on that actual element won't get blown away like they do on the children that are replaced inside, so the clicks will now work for current or future elements inside #navmenu.

Nick Craver