How to "Prevent Default" in HTML Inline "onclick" Event?

To prevent the default behavior of an inline onclick event in HTML, you can do either of the following:

Using event.preventDefault()

The event object is available inside the inline onclick event in HTML. You can use it to access various properties and methods related to the event that was triggered. Therefore, to prevent the default behavior of an inline onclick, you can simply call the preventDefault() method on the event object.

For example, consider the following anchor element, which prevents the browser from following the link and loading the URL when it is clicked:

<a
  href="https://www.google.com"
  onclick="event.preventDefault();"
>
    Google
</a>

Using return false

When you return false from an event handler, it has the same effect as calling the event.preventDefault() method — i.e., it prevents the default action associated with that event from occurring.

For example, consider the following anchor element, which prevents the browser from following the link and loading the URL when it is clicked:

<a
  href="https://www.google.com"
  onclick="return false;"
>
    Google
</a>

It's worth noting that returning false from an event handler not only prevents the default behavior, but also stops the event from propagating to other elements. This means that any other event handlers that are listening for the same event on parent elements will not be triggered.

While returning false can be a convenient way to prevent the default behavior of an element, it's generally recommended to use the event.preventDefault() method instead for more explicit and readable code.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.