Chris
Chris

Reputation: 3846

jQuery: triggers do not fire on elements loaded with .load()

I have index.php and use jQuery .load() to load content from load.php.

When I trigger an event on elements that are in the index.php, the event fires. On the same elements, when loaded with .load() into index.php the events do not fire!?

Why? Am I doing sth wrong?

If I preview the page with e.g. FireBug, the #id of the element is exactly like it should be, but not even a function like this works:

$('#clickme').click(function() {
    alert('hello');
});

The same function works, if the element is placed in the index.php and not loaded with .load(). Any ideas??

Thank you very much in advance!

Upvotes: 2

Views: 364

Answers (2)

user610217
user610217

Reputation:

The click event binder does not bind to any elements created after execution. You can add a click listener immediately following the .load() method, or you can use something like live or delegate to bind to element patterns in the DOM.

Upvotes: 2

James Montagne
James Montagne

Reputation: 78630

Using click will create an event listener on the element at the time it is called. if the element does not exist at the time click is called the listener is not created. You need to use event delegation using on (or delegate in older versions of jquery).

Have a look at the on documentation and read about delegation. You'll need something like this:

$("<selector of static ancestor>").on("click", "#clickme" , function(){})

Upvotes: 3

Related Questions