DEV Community

Voltra
Voltra

Posted on

1 1

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)

This post blew up on DEV in 2020:

js visualized

πŸš€βš™οΈ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! πŸ₯³

Happy coding!