1

How I can prevent any click event that has been assigned to an element?

I'm using a user custom javascript to alter a website. That script runs after the webpage is loaded.

How can I prevent a click event that has been bind to an element from triggering?

The binding procedure is opaque so I can't get the reference of the function. Also, element also has some other events bind to it, I want to keep them.

I simulated this situation with this snippet. I want hovering is shown when hovers but click is not shown while clicking. Is this possible?

const button = document.querySelector('button');

(() => {
  button.addEventListener('click', () => console.log('clicked'));
  button.addEventListener('mouseover', () => console.log('hovering'));
})();

// What do I do here to prevent the click event from being triggered?
<button>Click Me</button>
Hao Wu
  • 14,894
  • 4
  • 17
  • 48

1 Answers1

3

The event is dispatched in two phases, the default phase is the second one, "bubbling", so in this case you can add a listener in the first phase, "capturing", by setting the third parameter to true and stop the event from reaching the second phase:

button.addEventListener('click', e => e.stopPropagation(), true);
wOxxOm
  • 53,493
  • 8
  • 111
  • 119
  • Wow it actually works! I didn't know you can stop propagating from functions binded afterward, you saved my day! – Hao Wu Oct 06 '21 at 11:44