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,
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,
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>