I’m using the jQuery .load() function to pull in data to populate a div with. The content I’m pulling in has CSS selectors that should match up with jQuery click functions I’ve written. However, when I load in the data, although the correct CSS selectors are there, when I click on areas that should invoke a response from jQuery, nothing happens.
Do I need to do some sort of reload?
Here’s the code I’ve got for the jQuery AJAX:
$(document).ready(function() {
// AJAX functionality for drupal nodes
$(".ajax_node").click(function() {
var ajax_src = $(this).attr("href"); // we're gonna load the href
// empty target div and load in content
// the space in the string before the #id is necessary
$("#ajax_area").empty().load(ajax_src + " #ajax_wrapper");
return false; // stops the link from following through
});
// General AJAX functionality
$(".ajax").click(function() {
var ajax_src = $(this).attr("href");
$("#ajax_area").empty().load(ajax_src);
return false;
});
});
Instead of this format:
Use
.live()for current and future elements, like this:The why:
.live()listens for the event to bubble up at the DOM root, ordocument. It’s a single event handler bound there…it doesn’t matter when an element was added, they all bubble theclickthe same, when the click gets there: it checks the selector, if it matches it runs the handler.Why your current method doesn’t work: It’s finding all the elements that match that selector at that time and binding the handler…new elements aren’t there, so don’t get that handler. You have 2 options to solve this, either use
.live()which works in a different way, as described above, or re-bind the handler to that selector in the content of the request, like this:In your case, I think
.live()is much easier, you generally do the second with widgets and such, not strictly event handlers…but whatever floats your boat.