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>
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);