Event bubbling is Internet Explorer's
method of passing events along the document hierarchy. It works like this:
1. A user or particular condition causes an event
2. The event object is updated
3. An event is fired, and the handler called
4. The event handler bubbles up to the next element in the heirarchy, unless it's the current
element is the window object
5. The default event handler is called.
An important thing to note is that once we reach step 3, we can prevent steps 4 and/or 5 from taking place
by *cancelling the bubble and/or returning false*.
A simple example of how event bubbling works is in the following document:
function mouseOutHandler()
{
window.event.srcElement.style.backgroundColor='blue'
}
</script>
</head>
<body>
<div onmouseover="mouseOverHandler()" onmouseout="mouseOutHandler()">
<span style="background-color:blue;color:white">
This one will change.
</span>
<br>
<span onmouseout="window.event.cancelBubble=false"
onmouseover="window.event.cancelBubble=true" style="background-color:blue;color:white">
This one will <b>not</b> change.
</span>
<br>
<span style="background-color:blue;color:white">
This one will change.
</span>
</div>
</body>
</html>
Notice, we have not explicity set any event handlers for the 'SPAN' tags here, but the same functionality is
produced that we would have achieved by explicitily setting an event handler for each span. This is because
the event starts at the span, but then bubbles up to the container 'DIV' above it. Notice also that
the second span will not change color when you mouseover it. This is because we assigned a particular event
handler to that one:
window.event.cancelBubble=false
That line will prevent the event from bubbling up the document hierarchy and reaching the handler in the 'DIV'
that contains it. Therefore, no action is taken.
Another interesting technique we can use is returning false in our own event handlers. This will prevent
whatever the default action of the event is from occuring. Take the following document as an example:
<html>
<head>
<title>Event Handler Test</title>
</head>
<body>
<a href="javascript:alert('Told ya!')">
This one will alert.
</a>
<br>
<a href="javascript:alert('Told ya!')">
This one will alert.
</a><br>
<a href="javascript:alert(this.href)" onClick="this.innerText='Told Ya!';return false">
This one will not alert.
</a>
</body>
</html>
Notice that clicking on the first two links will allows the default action to occur, while clicking on the third
one prevents the default action from taking place. We achieved this by using:
return false
in the event handler.
Please note that these examples are very contrived, and that real-world applications of these concepts
may be a bit more complex. I chose to keep them simple so they would be easy to understand.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.