Cancel event with preventDefault in JavaScript
Description
The following code shows how to cancel event with preventDefault.
Example
<!-- ww w . java 2 s. c o m-->
<!DOCTYPE HTML>
<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>
The code above generates the following result.
Javascript Tutorial Browser Event
Access window event in JavaScript
Add event handler for body onload event in ...
Add event handler for window on load event ...
Add onload event handler by using attribute...
Filter event to catch in JavaScript
Handle Error event on body in JavaScript
Handle browser window resize event in JavaS...
Handle document on changed event in JavaScr...
Handler document on abort event in JavaScri...
Access window event in JavaScript
Add event handler for body onload event in ...
Add event handler for window on load event ...
Add onload event handler by using attribute...
Cancel event with preventDefault in JavaScr...
Filter click event to capture in JavaScriptFilter event to catch in JavaScript
Handle Error event on body in JavaScript
Handle browser window resize event in JavaS...
Handle document on changed event in JavaScr...
Handler document on abort event in JavaScri...