remove all events attached to a selector, immediately add a new

61 Views Asked by At
$('.home')
  .unbind('click') 
  .attr('onclick', '') 
  .each(function() { 
    this.onclick = null;
  });

I have found the above jQuery works, but I would like to immediately add a new function after this; and ideally a non-jQuery or ES6/ES7 technique.

1

There are 1 best solutions below

0
CertainPerformance On

unbind (deprecated) or off will remove all listeners attached via jQuery, so you can add another listener with jQuery by using .on right afterwards:

$('.home')
  .off('click') // remove listeners attached via jQuery
  .attr('onclick', '') // remove listeners attached via inline attribute
  .each(function() {
    this.onclick = null; // remove listeners attached via assigning to onclick of element
  })
  .on('click', () => console.log('click'));

If a listener isn't added via jQuery, and you don't save a reference to the function when it gets added, you can't remove it with addEventListener. The only other option would be to completely remove the element (though that would also remove any other non-click listeners the element may have). For example, if a listener is attached via:

document.querySelector('.home').addEventListener('click', () => console.log('click'));

then it will not be possible to remove afterwards, unless you completely remove the element from the DOM and replace it with something else..