1

Any ideas what could be the reason that the code

$('body').on('click', '.btn_add', function(e) {alert("test");});

works, but

$('.btn_add').on('click', function(e) {alert("test");});

does not?

Thanks,

amit
  • 2,171
  • 4
  • 31
  • 50
  • 1
    that is called event delegation. – Jai Mar 16 '15 at 09:59
  • 1
    It's because the `.btn_add` element is not part of the DOM when the handler is added. For more information see: http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – Rory McCrossan Mar 16 '15 at 10:00

1 Answers1

3

It is event delegation:

Syntax is :

$(staticparent).on(event, selector, fn);

in this syntax selector is not a part of DOM, what it means when your page loaded this element was not there in the dom but after some js code execution this .btn_add element added in the DOM. so any event bound on page load won't be registered for this element.

so in your case if .btn_add is created dynamically then you have to delegate the event to the closest static parent, body or to document itself.

Here is a test case for event not bound on dynamic content.

$('button').on('click', function() {
  $('<button/>', {
    text: "Dynamic button"
  }).appendTo('body');
  alert(this.textContent);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Static</button>

Here is a test case for event bound on dynamic content.

$('body').on('click', 'button', function() {
  $('<button/>', {
    text: "Dynamic button"
  }).appendTo('body');
  alert(this.textContent);

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Static</button>
Jai
  • 74,255
  • 12
  • 74
  • 103