preventDefault: Cancellable Events

Some events define a default action when an event is triggered. For example, the default action for clicking a element is to navigate to the URL. When an event has a default action, the value of its cancelable property will be true.

You can stop the default action by calling the preventDefault function.

 
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
<style type="text/css">
a {
  background: gray;
  color: white;
  padding: 10px;
  border: thin solid black
}
</style>
</head>
<body>
    <a href="http://java2s.com">Visit java2s.com</a>
  <script type="text/javascript">
    function handleClick(e) {
      if (!confirm("Do you want to navigate to " + e.target.href + " ?")) {
        e.preventDefault();
      }
    }
    var elems = document.querySelectorAll("a");
    for ( var i = 0; i < elems.length; i++) {
      elems[i].addEventListener("click", handleClick, false);
    }
  </script>
</body>
</html>
  
Click to view the demo

Calling the preventDefault function doesn't stop the event from flowing through the capture, target, and bubble phases.

The defaultPrevented property returns true, if the preventDefault function has been called.

Home 
  JavaScript Book 
    DOM  

DOM Event:
  1. The DOM Events
  2. Event Flow: capture, target, and bubbling
  3. eventPhase
  4. preventDefault: Cancellable Events
  5. Events Type
  6. Event Target