Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104781

Proper way to attach handlers with jQuery

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:

  1. The handler is always attached to all the buttons satisfying the jQuery selector, even those who were just loaded to the page via ajax
  2. The handler is not attached zillion times to each element on each ajax call
  3. What is the general convention to make my entire website handled via jQuery classes instead of inline 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

Answers (1)

Blender
Blender

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

Related Questions