Hao Wu
Hao Wu

Reputation: 20953

Remove only click events from an element

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>

Upvotes: 1

Views: 141

Answers (1)

woxxom
woxxom

Reputation: 73856

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

Upvotes: 3

Related Questions