Demonstrate Event Bubbling in JavaScript

Description

The following code shows how to demonstrate Event Bubbling.

Example


<!--from   w  w  w. ja  v  a 2s .c o  m-->
<html onclick="alert('Event is now at the HTML element.')">
<head>
<script type="text/javascript">
function init() {
window.onclick = winEvent
document.onclick = docEvent;
document.body.onclick = docBodEvent;
}
function winEvent() {
alert("window object level.");
}
function docEvent() {
alert("document object level.");
}
function docBodEvent() {
alert("BODY element.");
}
</script>
</head>
<body onload="init()">
<form onclick="alert('FORM')">
<input type="button" value="Button 'main1'" name="main1" onclick="alert('Button: ' + this.name)" />
</form>
</body>
</html>

Click to view the demo

The code above generates the following result.

Demonstrate Event Bubbling in JavaScript