Baptiste Arnaud
Baptiste Arnaud

Reputation: 2750

e.preventDefault() not working in 100% cases

I'm trying to disable every click events on a web pages.

document.addEventListener("click", function (e) {
    e.preventDefault();
    e.stopImmediatePropagation();
    let clicked = e.target;
    console.log(clicked);
  });

This is supposed to prevent every click event right? But I still find cases where it is ignored (mostly with links).

What am I missing?

Upvotes: 5

Views: 13146

Answers (2)

Jonno
Jonno

Reputation: 556

My experience was that the button in question, that I was in the process of binding an onclick event to, through jQuery (and attempting to use e.preventdefault(); on, to stop the incorrectly assumed form post from happening), was executing inline onclick javascript code (ie. onclick="window.location.href='www.xxx.xx'").

I didn't carefully inspect the button, and see this. I just assumed that it was a submit button in a FORM, and couldn't figure out why e.preventdefault was failing.... executing the form post, and bypassing my new event binding.

I guess the same might be true if it wasn't an inline window.location.href='www.xxx.xx', and just had an event binding from code somewhere else?

Upvotes: 0

Thomas
Thomas

Reputation: 6680

The problem here is at what stage the event is captured by your handler (or intercepted). The code in your question is being executed for events that bubble up to the document (events whose propagation has not been stopped by elements further down the document tree) during the final phase of propagation, not for all events that occur on document (what you are after).

In your case, you effectively want to stop the execution of the event for all descendants during the "capture" phase - look at Section 3.1 - (the first phase of event propagation).

Add true to the call to execute in the capture phase:

document.addEventListener("click", function (e) {
 // ...
}, true);

You should also only need e.stopImmediatePropagation() in your handler.

Upvotes: 9

Related Questions