-2
$('.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.

Dr Upvote
  • 8,023
  • 24
  • 91
  • 204
  • not sure to understand... how looks the HTML for this ? – Mister Jojo Mar 09 '20 at 01:53
  • Why do you consistently insist on ridiculous techniques? ES6 is fine, by the way. jQuery on the other hand, is not necessary since CSS3, querySelector and querySelectorAll came out. – StackSlave Mar 09 '20 at 01:55

1 Answers1

1

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..

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320