Prevent event Bubble and Capture in JavaScript
Description
The following code shows how to prevent event Bubble and Capture.
Example
<html>
<head>
<script type="text/javascript">
function init() {<!--from ww w . java2s . c om-->
document.body.onclick = docBodEvent;
document.addEventListener("click", docEvent, true);
document.forms[0].addEventListener("click", formCaptureEvent, true);
document.forms[0].addEventListener("click", formBubbleEvent, false);
}
function docBodEvent(evt) {
if (evt.target.type == "button") {
alert("BODY");
}
}
function formCaptureEvent(evt) {
if (evt.target.type == "button") {
alert("This alert triggered by FORM only on CAPTURE.");
if (document.forms[0].stopAllProp.checked) {
evt.stopPropagation();
}
}
}
function formBubbleEvent(evt) {
if (evt.target.type == "button") {
alert("This alert triggered by FORM only on BUBBLE.");
if (document.forms[0].stopDuringBubble.checked) {
evt.preventBubble();
}
}
}
</script>
</head>
<body onload="init()">
<form>
<input type="checkbox" name="stopAllProp" />Stop all propagation at FORM
<input type="checkbox" name="stopDuringBubble" />Prevent bubbling past FORM
<input type="button" value="Button 'main1'" name="main1" onclick="alert('button')" />
</form>
</body>
</html>
The code above generates the following result.
Javascript Tutorial Event Basic
Add click event handler to form and check t...
Check Event bubble phase in JavaScript
Check event type in JavaScript
Create your own event in JavaScript
Demonstrate Event Bubbling in JavaScript
Demonstrate Event Capture and Bubble and ev...
Find out event handling and firing phases i...
Get element id through event object in Java...
Get event Phase in JavaScript
Get event source element name and id in Jav...
Get the event target in JavaScript
Get the event type for key event in JavaScr...
Get the event type from event in JavaScript
Get the source tag name which triggered the...
Show the event capture phase in JavaScript
Stop Event Propagation in JavaScript
Tell if the event supports bubble with Even...
Test the event bubbling in JavaScript
Add click event handler to form and check t...
Check Event bubble phase in JavaScript
Check event type in JavaScript
Create your own event in JavaScript
Demonstrate Event Bubbling in JavaScript
Demonstrate Event Capture and Bubble and ev...
Find out event handling and firing phases i...
Get element id through event object in Java...
Get event Phase in JavaScript
Get event source element name and id in Jav...
Get the event target in JavaScript
Get the event type for key event in JavaScr...
Get the event type from event in JavaScript
Get the source tag name which triggered the...
Prevent event Bubble and Capture in JavaScr...
Remove a certain type of event listener fro...Show the event capture phase in JavaScript
Stop Event Propagation in JavaScript
Tell if the event supports bubble with Even...
Test the event bubbling in JavaScript