Code
JavaScript code
//If an event object is provided, this is a non-IE browser
if (e && e.stopPropagation)
//So it supports W3C's stopPropagation() method
e.stopPropagation();
else
//Otherwise, we need to use IE to cancel event bubbling
window.event.cancelBubble = true;
return false;
2. Prevent the browser's default behavior
JavaScript code
//If an event object is provided, this is a non-IE browser
if (e && e.preventDefault)
//Block default browser actions (W3C)
e.preventDefault();
else
//How to prevent the default action of function in IE
window.event.returnValue = false;
return false;
Code
1<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" " http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
2<html xmlns=" http://www.w3.org/1999/xhtml " lang="gb2312">
3<head>
4<title> Prevent JavaScript events from bubbling (cancelBubble, stopPropagation)</title>
5<meta name="keywords" content="JavaScript, event bubbling, cancelBubble, stopPropagation" />
6<script type="text/javascript">
7function doSomething (obj,evt) {
8alert(obj.id);
9var e=(evt)?evt:window.event;
10if (window.event) {
11e.cancelBubble=true;
12} else {
13//e.preventDefault();
14e.stopPropagation();
15}
16}
17</script>
18</head>
19<body>
20<div id="parent1" onclick="alert(this.id)" style="width:250px;background-color:yellow">
21<p>This is parent1 div.</p>
22<div id="child1" onclick="alert(this.id)" style="width:200px;background-color:orange">
23<p>This is child1.</p>
24</div>
25<p>This is parent1 div.</p>
26</div>
27<br />
28<div id="parent2" onclick="alert(this.id)" style="width:250px;background-color:cyan;">
29<p>This is parent2 div.</p>
30<div id="child2" onclick="doSomething(this,event);" style="width:200px;background-color:lightblue;">
31<p>This is child2. Will bubble.</p>
32</div>
33<p>This is parent2 div.</p>
34</div>
35</body>
36</html>