Skip to content

JavaScript preventDefault() Event Method

  • by

Using JavaScript preventDefault() Event Method, you can prevent the default action of an event. This method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

event.preventDefault();

JavaScript preventDefault() Event Method

Simple example code call the preventDefault() method of the event object to not change its state to be checked.

<!DOCTYPE html>
<html>
<body>
  <input type="checkbox" name="ckAgree" id="ckbox"> Agree
  
  <script>
    const ck = document.querySelector('#ckbox');

    ck.addEventListener('click', function (e) {
      alert('Sorry! you cannot check this preventDefault.');
      e.preventDefault();
    });
  </script>
</body>
</html>

Output:

JavaScript preventDefault Event Method

How to prevent default event handling in an onclick method?

Answer: Let your callback return false and pass that on to the onclick handler:

<a href="#" onclick="return callmymethod(24)">Call</a>

function callmymethod(myVal){
    //doing custom things with myVal
    //here I want to prevent default
    return false;
}

Do comment if you have any doubts or suggestions on this Js event method topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *