DOM - Event PreventDefault

Card Puncher Data Processing

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

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

On Content Attribute

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>







Share this page:
Follow us:
Task Runner