Few people knows how events works in javascript. Currently, many people use frameworks, and do not realize how event works, so they are spend much time on simple things.
I’ll tell about a widely known in narrow circles thing such as event bubbling. What I’m talking about?
When we are click on any element on the web page, the event is raised on all the parent nodes of clicked element, until it reaches the document node. This is event bubbling as is.
Let’s see clearly how it works, it’s better to see than tell a thousand words.
We have a HTML markup:
<div id="dialog">
I'm a absolutely positioned dialog. So click me!
</div>
We have a CSS:
<style type="text/css">
#dialog {
padding: 200px;
position: absolute;
top: 100px;
left: 100px;
border: 1px solid #000;
background: #ddd;
}
</style>
And, most importantly, there is javascript (JQuery):
<script type="text/javascript">
$(document).ready(function() {
$('#dialog').click(function(e) {
alert('Clicked on dialog!');
})
$(document).click(function(e) {
alert('Clicked on document!');
})
});
</script>
As we can see, we have callbacks on dialog click and on document click. Now let’s open a working example and click on the dialog. What happened? As a result we’ve got 2 alerts: alert from dialog and from document. Why this happened, we’re just clicked on the dialog? The reason is in the event bubbling!
So let’s do that when we click on the dialog, then appeared only alert for this dialog. All we need to do is to cancel the event bubbling, so that the event did not rise up the DOM nodes. This can be done simply by adding e.stopPropagation() to dialog click callback. That’s all. Let’s see final sample.
So, this is a simple thing - but few know about it. It greatly simplifies the development on javascript. How, for example, without any distortions /you can hide any element by click out of this element/ to make any element on the page when they click into hiding outside this item? Only through event bubbling! Now you know :)
CU.
Also interesting
Tags: dom, event bubbling, javascript, jquery
well the demo u gave has some error
even when i press on text it says clicked on Document and text
bith javascripts are coming up ( alert boxes )
please check it
Ok, thanks. Which browser you are watchin this demo?
using Firefox 3.5.6
well now it only shows Clicked on Dialog
where ever i press it only shows Clicked on Dialog ( it aint showing Document )
Here is http://torqueo.net/files/event-bubbling/okay.html correct behaviour. When you click on the Dialog in this demo, you will see only “Clicked on dialog” alert message, but the message “Clicked on document” should not appear, reason is that we abolish the onclick event propagation to document (e.stopPropagation() method).
I checked this demo (http://torqueo.net/files/event-bubbling/okay.html) in IE6, FF 3.5.5 and Google Chrome - in these browsers my sample is working correctly.