0

Normally, if I wanted to call a function if a link is clicked, I would do this:

$('a').click(function() {
    //stuff
});

However, I need to call this function even if the element has been newly added. For example,

$('a').click(function() {
    //stuff
});
$(document.body).append($('<a href="http://example.com">This is an example</a>'))
//now when I click that example link, the function isn't called!

How can I make a function that applies to all links? I do not have control of the code that adds the new links, so I can't just set its onclick when it's added.

Fiddle

tckmn
  • 52,184
  • 22
  • 101
  • 145

2 Answers2

4

Use event delegation for registering events for dynamically added elements using .on()

$(document).on('click', 'a', function() {
    //stuff
});

Demo: Fiddle

Arun P Johny
  • 365,836
  • 60
  • 503
  • 504
4

You need to delegate your click event using .on() like:

$(document).on('click', 'a', function(){...});

Per the doc for .on():

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

Note that using $(document) is considered a worst case example and you want to use an element closer in the DOM whenever possible.

Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.

j08691
  • 190,436
  • 28
  • 232
  • 252