How to cancel event from Javascript

Description

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.

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.

Example


<!DOCTYPE HTML>
<html>
<head>
<style type="text/css">
a {<!--from   w  w w.j a v a2  s .c om-->
  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





















Home »
  Javascript »
    Javascript Reference »




Array
Canvas Context
CSSStyleDeclaration
CSSStyleSheet
Date
Document
Event
Global
History
HTMLElement
Input Element
Location
Math
Number
String
Window