Search code examples
javascriptjquerydelegatesevent-delegation

Remove jQuery delegated event handler on specific object


I've attached delegated event handlers to a number of elements on the page using a single selector. As the events are triggered for individual elements, I'd like to turn off only that element's event handler based on some conditional logic. That means I won't necessarily want to disable the event on the very first click. But I can't figure out how to do it without turning off all of them.

HTML:

<button>One</button>
<button>Two</button>
<button>Three</button>

JS:

$(document).on('click', 'button', function(ev) {
    // doesn't work because argument needs to be a string
    $(document).off('click', $(ev.target));

    // doesn't do what I want b/c turns off events on all buttons, not just this one
    $(document).off('click', 'button');

    // doesn't work because event is on document, not button
    $(ev.target).off('click');
});

jQuery's off documentation says I need to provide a string as the second argument, not a jQuery object ($(ev.target)), but if I provide a string, there's no value that refers only to the item clicked.

From jQuery's off documentation:

To remove specific delegated event handlers, provide a selector argument. The selector string must exactly match the one passed to .on() when the event handler was attached. To remove all delegated events from an element without removing non-delegated events, use the special value "**".

So how do I turn off a delegated event handler for a specific element?

Here's a JSFiddle of the code above

UPDATE: Added a few examples of options that don't work, based on initial answers provided.


Solution

  • After having read thru on the web, the answer is you can't! You can either remove all or none. A workaround could be something like the following.

    $(document).on('click', '.btn', function (ev) {
        alert('pressed');
        $(this).removeClass("btn");
    });
    

    Demo@Fiddle

    Sample HTML:

    <button class="btn">One</button>
    <button class="btn">Two</button>
    <button class="btn">Three</button>