DEV Community

Voltra
Voltra

Posted on

What is e.defaultPrevented and why library authors MUST use it

Event#defaultPrevented is, as per MDN, a flag available on an event to know whether its default action was prevented (regardless of whether Event#preventDefault was called, but calling it will set the flag to true).

Why do library authors need to use it? Because a listener added by the user calling e.preventDefault() will not prevent your listeners from being called.

@dogstudio/highway is one such library that doesn't check for that, and thus preventing the default behavior of an anchor will not prevent further navigation.

Using e.defaultPrevented is here to ensure everyone can safely add listeners and execute them only if they should.

Should browsers make the check for you? Maybe, but it might get freedom away for some use cases. In the meantime, please check for the flag.

Top comments (0)