Categories
JavaScript Answers

How to Unbind Event Handlers to Bind Them Again Later with jQuery?

Spread the love

To unbind event handlers to bind them again later with jQuery, we can use the _data to get the event bindinds.

Then we can get the click event binding with the click property.

For instance, if we have:

<a id="test">test</a>

Then we write:

$(document).ready(() => {
  $('#test').click((e) => {
    const events = $._data($('#test')[0], 'events');
    $('#test').unbind('click', events.click[0]);
  });
});

to add the click event listeners with the click method.

In the click event handler callback, we get the bindings with:

$._data($('#test')[0], 'events')

and assign it to events.

Then we unbind the click event handler with:

$('#test').unbind('click', events.click[0]);

Then when we want to bind to the click event, we can use the events to bind the event again.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *