Cancel events

In this chapter you will learn:

  1. How to use preventDefault to cancel events

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><!--  j  a v a 2  s.c o  m-->
<html>
<head>
<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.

Next chapter...

What you will learn in the next chapter:

  1. Get the Events Type
Home » Javascript Tutorial » DOM Event
DOM Events
Event Flow: capture, target, and bubbling
Event Phase
Cancel events
Events Type
Event Target