1
$(function(){
    $('div').append('<a>link</a>');

  $('a').click(function(){
    alert('trigger <a>!');
  });
});

https://jsfiddle.net/nj6Lsgo1/

Why does the <a> trigger in my case? I thought I have to use binding like .on() for incoming elements.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Jennifer
  • 905
  • 9
  • 20
  • The order of the script is the reason... before the `click` handler is added you are adding the `anchor` element to dom... if you move the `append()` to after the `click` then it won't work - https://jsfiddle.net/arunpjohny/n173pqwf/1/ – Arun P Johny Jan 06 '16 at 05:23
  • https://jsfiddle.net/arunpjohny/n173pqwf/2/ – Arun P Johny Jan 06 '16 at 05:24

1 Answers1

2

Why does the <a> trigger in my case?

The event is simply being triggered because you are attaching the click event listener after appending the anchor element to the DOM.

In other words, $('a').click(function() {...}); will attach the click event listener to all a elements that exist in the DOM at that time.

Since the a element has already been appended, the click event listener is attached.

I thought I have to use binding like .on() for incoming elements

You only need to delegate the event listener if you are attaching an event listener before the element exists in the DOM.

For instance, if you were to reverse the logic and append the element directly after attaching the event listener, it simply wouldn't work:

// This wouldn't be fired since the element is 
// appended after the event listener is attached

$('a').click(function() {
  alert('trigger <a>!');
});

$('div').append('<a>link</a>');

Which is why you would need to delegate the event listener to an ancestor element that does exist in the DOM at that time:

$('div').on('click', 'a', function() {
  alert('trigger <a>!');
});

$('div').append('<a>link</a>');
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304