Reputation: 104781
I have a page with many buttons, many of which I add after the initial jQuery loading, using ajax.
I have some handlers in my script.js
file, here is one:
$('.editor-button.remove').click(function () {
var row = $(this).parent('.row');
row.remove();
});
How can I make sure:
onclick
handlers, is this a bad habit? First two questions apply to this one too obviously.I'm pretty new to event-handling via jQuery concept, I want to keep script.js
as clean as possible not polluting it with localized stuff, in the other hand, I want my buttons to contain only class names, not ciphered functions etc. General rule is my code should be as clean as possible while each handler isn't attached zillion times with each ajax call.
I'm not looking for a solution to the issue I mentioned above, but rather for general guidelines on how to treat jQuery handlers as efficiently and clean as possible.
Upvotes: 0
Views: 135
Reputation: 298402
Event delegation is what you're after:
$('#parent').on('click', '.editor-button.remove', function() {
$(this).closest('.row').remove();
});
Make sure that #parent
is present when the event handler is attached. If there is none, use document
.
By attaching the event handler to #parent
, events triggered by the children will be delegated to the parent and accepted if the targeted element matches your selector. This will take into account dynamically created elements and won't even attach an event handler to those children to begin with.
Upvotes: 5