Many events automatically lead to certain actions performed by the browser.
For instance:
- A click on a link – initiates navigation to its URL.
- A click on a form submit button – initiates its submission to the server.
- Pressing a mouse button over a text and moving it – selects the text.
If we handle an event in JavaScript, we may not want the corresponding browser action to happen, and want to implement another behavior instead.
Preventing browser actions
There are two ways to tell the browser we don’t want it to act:
- The main way is to use the
eventobject. There’s a methodevent.preventDefault(). - If the handler is assigned using
on<event>(not byaddEventListener), then returningfalsealso works the same.
In this HTML a click on a link doesn’t lead to navigation, browser doesn’t do anything:
<a href="/" onclick="return false">Click here</a>
or
<a href="/" onclick="event.preventDefault()">here</a>
event.defaultPrevented
The property event.defaultPrevented is true if the default action was prevented, and false otherwise.
There’s an interesting use case for it.
You remember in the chapter Bubbling and capturing we talked about event.stopPropagation() and why stopping bubbling is bad?
Sometimes we can use event.defaultPrevented instead, to signal other event handlers that the event was handled.
Let’s see a practical example.
By default the browser on contextmenu event (right mouse click) shows a context menu with standard options. We can prevent it and show our own, like this:
<button>Right-click shows browser context menu</button>
<button oncontextmenu="alert('Draw our menu'); return false">
Right-click shows our context menu
</button>