Table of Contents

About

If you don't want to have the default beahavior (such as following a link), you can prevent it with the event.preventDefault() function.

It still allow the event propagation but disable the default action.

Example

IDL

DOM Event Handler - On Properties with Javascript (Interface Definition Language - IDL )

  • The HTML link that will not work anymore
<p>Clicking on the below link will not work</p>
<a href="https://gerardnico.com">Go to the best website on the planet</a>
  • The javascript code to prevent the default behavior with the event.preventDefault() function
document.querySelector('a').onclick = function(event) {
       console.log( "You are no longer following the link" );
       event.preventDefault();
}

Inline

What are the HTML On Attributes ? (known also as event handler content attributes)

Passing the event as parameter

function prevent(event){
   event.preventDefault();
}
<p>Clicking on the below link will not work</p>
<a href="https://datacadamia.com" onClick="prevent(event)">Go to the best website on the planet</a>

Returning false

If the expression returns false, the event will be consumed, preventing the browser from performing any default action.

<p>Clicking on the below link will not work</p>
<a href="https://datacadamia.com" onClick="return false;">Go to the best website on the planet</a>