DigitalMC
DigitalMC

Reputation: 877

Removing ".on" Click Event in jQuery using 'selector;

I am using jQuery's ".on" to attach a click even to a "More Items" button. This event may get re-attached multiple time due to the way our script processes.

I want to prevent multiple events from firing when this button is clicked. I'm actually attaching the event to "document" and using a selector to target the button. Again this is because of reloads and ajax calls I keep the event on "document" so it's never lost.

Below is my code:

  // Removes previous events 
  $(document).off('click','.moreItems');

 // Attached new event
  $(document).on('click','.moreItems', function(event) {
    ... do stuff ....
  });

I've scoured stack voerflow for an answer but nothing helped. Everything talks about removing the event from the initial object ("document" in this case) but never using a selector (that I could find).

Thanks!

Upvotes: 0

Views: 74

Answers (3)

schellingerht
schellingerht

Reputation: 5796

I don't understand your question.

$(document).on('click','.moreItems', function(event) {
   ... do stuff ....
});

You delegate the click event to document. If you add dynamically elements with class 'moreItems', the click event has been binded automatically.

See the official documentation: http://api.jquery.com/on/

Never do this:

  • first unbind, next bind
  • multiple bind on same element

Upvotes: 1

Alex W
Alex W

Reputation: 38173

If you keep a reference to the callback function, you can remove all instances of it with .off():

var callback = function(){console.log('callback executed');};

jQuery('.moreItems').on('click',callback);
jQuery('.moreItems').on('click',callback);

jQuery('.moreItems').off('click',callback);

Fiddle

Upvotes: 2

fray88
fray88

Reputation: 820

I will use unbind and bind instead off and on beside I think they are alias of the same function, also append the event to the object, not to the document itself, but that should be optional.

$('.moreItems').unbind('click').bind('click', function(event) {
   //Your code
});

When you call unbind with only the event type as parameter, it will remove all the handlers of that event, I guess that's also what you want.

Upvotes: 0

Related Questions