Reputation: 1263
In the following code, I can't tell why my console prints 'hi' when I click on a button with the class 'edit-button' for the first time. The second time I'm expecting it to print the console because the 'update-now' class has been added to the button. Does anyone understand why this is? Thanks!
$(function() {
$('.edit-button').on('click', function(e) {
$( this ).addClass('update-now').html('Update');
});
});
$(document).on('click', "div.update-now", function() {
console.log('hi');
});
Upvotes: 3
Views: 148
Reputation: 67207
This is happening because of event propagation. Basically event delegation works with the use of event bubbling. Now in your case, you bound an event to .update-now
by using event delegation signature.
And you are adding a class update-now
to another one button inside its click event, so that event propagates until it meets the document and after that it will investigate who raised the event. Here div with class update-now
has started the propagation. So the event handler got triggered and prints hi in the console.
So if you stop the propagation after/before adding the class update-now
, the hi
message will not be printed,
$('.edit-button').on('click', function(e) {
$( this ).addClass('update-now').html('Update');
e.stopPropagation()
});
A solution for your case that i would suggest,
$('.edit-button').on('click', function(e) {
$( this ).addClass('update-now').html('Update');
$(this).off("click");
e.stopPropagation();
});
$('body').on('click', ".edit-button.update-now", function() {
alert('hi');
});
Upvotes: 4