http://www.quirksmode.org/js/events_order.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head>
<title>Javascript - Event order</title>
<link rel="stylesheet" href="../quirksmode.css" />
<link rel="up" href="contents.html" />
<link rel="intro" href="introevents.html" />
<link rel="prev" href="events_properties.html" />
<link rel="next" href="events_mouse.html" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="../quirksmode.js"></script>
</head>

<body>

<h2>Event order</h2>

<div id="header"></div>

<div class="floater">
<p>See section 7D of <a href="/book/">the book</a>.</p>
<p>Netscape 4 only supports event capturing, Explorer only supports event bubbling.
Netscape 6 and Konqueror support both, while Opera and iCab support neither.</p>
</div>

<p class="intro">On the <a href="introevents.html">Introduction to events</a> page
I asked a question that at first sight seems incomprehensible:
&#8220;If an element and one of its ancestors have an event handler for the same event, which
one should fire first?&#8221; Not surprisingly, this depends on the browser.</p>

<p>The basic problem is very simple. Suppose you have a element inside an element</p>

<pre>
-----------------------------------
| element1                        |
|   -------------------------     |
|   |element2               |     |
|   -------------------------     |
|                                 |
-----------------------------------
</pre>

<p>and both have an onClick event handler. If the user clicks on element2 he causes
a click event in both element1 and element2. But which event fires first? Which event handler should
be executed first? What, in other words, is the <em>event order</em>?</p>

<h3>Two models</h3>

<p>Not surprisingly, back in the bad old days Netscape and Microsoft came to different conclusions.</p>

<ul><li>Netscape said that the event on element1 takes place first. This is called
event <em>capturing</em>.</li>
<li>Microsoft maintained that the event on element2 takes precedence. This is called
event <em>bubbling</em>.</li>
</ul>

<p>The two event orders are radically opposed. Explorer
only supports event bubbling. Mozilla, Opera 7 and Konqueror support both. Older Opera's and
iCab support neither.</p>

<h4>Event capturing</h4>

<p>When you use event capturing</p>

<pre>
               | |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------
</pre>

<p>the event handler of element1 fires first, the event handler of element2 fires last.</p>


<h4>Event bubbling</h4>

<p>When you use event bubbling</p>

<pre>
               / \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------
</pre>

<p>the event handler of element2 fires first, the event handler of element1 fires last.</p>

<h3>W3C model</h3>

<p>W3C has very sensibly decided to take a middle position in this struggle.
Any event taking place in the
<a href="http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/"
	class="external" >W3C event model</a> is first captured until it
reaches the target element and then bubbles up again.</p>

<pre>
                 | |  / \
-----------------| |--| |-----------------
| element1       | |  | |                |
|   -------------| |--| |-----------     |
|   |element2    \ /  | |          |     |
|   --------------------------------     |
|        W3C event model                 |
------------------------------------------
</pre>

<p>You, the web developer, can choose whether to register an event handler in the capturing or
in the bubbling phase. This is done through the <code>addEventListener()</code>
method explained on the <a href="events_advanced.html">Advanced models</a> page.
If its last argument is <code>true</code> the event handler is set for the capturing phase, if it is
<code>false</code> the event handler is set for the bubbling phase.</p>

<p>Suppose you do</p>

<pre>
element1.addEventListener('click',doSomething2,true)
element2.addEventListener('click',doSomething,false)
</pre>

<p>If the user clicks on element2 the following happens:</p>

<ol>
<li>The <code>click</code> event starts in the capturing phase. The event looks if any
ancestor element of element2 has a <code>onclick</code> event handler for the capturing
phase.</li>
<li>The event finds one on element1. <code>doSomething2()</code> is
executed.</li>
<li>The event travels down to the target itself, no more event handlers for the capturing
phase are found. The event moves to its bubbling phase and executes <code>doSomething()</code>,
which is registered to element2 for the bubbling phase.</li>
<li>The event travels upwards again and checks if any ancestor element of the
target has an event handler for the bubbling phase. This is not the case, so nothing happens.</li>
</ol>


<p>The reverse would be</p>

<pre>
element1.addEventListener('click',doSomething2,false)
element2.addEventListener('click',doSomething,false)
</pre>

<p>Now if the user clicks on element2 the following happens:</p>

<ol>
<li>The <code>click</code> event starts in the capturing phase. The event looks if any
ancestor element of element2 has a <code>onclick</code> event handler for the capturing
phase and doesn&#8217;t find any.</li>
<li>The event travels down to the target itself.
The event moves to its bubbling phase and executes <code>doSomething()</code>,
which is registered to element2 for the bubbling phase.</li>
<li>The event travels upwards again and checks if any ancestor element of the
target has an event handler for the bubbling phase.</li>
<li>The event finds one on element1. Now <code>doSomething2()</code> is executed.</li>
</ol>

<h4>Compatibility with traditional model</h4>

<p>In the browsers that support the W3C DOM, a traditional event registration</p>

<pre>
element1.onclick = doSomething2;
</pre>

<p>is seen as a registration in the <em>bubbling phase</em>.</p>


<h3>Use of event bubbling</h3>

<p>Few web developers consciously use event capturing or bubbling. In Web pages as they are made
today, it is simply not necessary to let a bubbling event be handled by several different event handlers.
Users might get confused by several things happening after one mouse click, and usually you want
to keep your event handling scripts separated. When the user clicks on an element, something happens,
when he clicks on another element, something else happens.</p>

<p>Of course this might change in the future, and it&#8217;s good to have models available that
are forward compatible. But the main practical use of event capturing and bubbling today
is the registration of default functions.</p>

<h3>It always happens</h3>

<p>What you first need to understand is that event capturing or bubbling always happens.
If you define a general onclick event handler for your entire document</p>

<pre>
document.onclick = doSomething;
if (document.captureEvents) document.captureEvents(Event.CLICK);
</pre>

<p>any <code>click</code> event on any element in the document will eventually bubble up to the document and
thus fire this general event handler.
Only when a previous event handling script explicitly orders the event to stop bubbling, it will not propagate to the
document.</p>

<h3>Uses</h3>

<p>Because any event ends up on the document, default event handlers become possible.
Suppose you have this page:</p>

<pre>
------------------------------------
| document                         |
|   ---------------  ------------  |
|   | element1    |  | element2 |  |
|   ---------------  ------------  |
|                                  |
------------------------------------

element1.onclick = doSomething;
element2.onclick = doSomething;
document.onclick = defaultFunction;
</pre>

<p>Now if the user clicks on element1 or 2, <code>doSomething()</code> is executed. You can
stop the event propagation here, if you wish. If you don&#8217;t the event bubbles up to
<code>defaultFunction()</code>.
If the user clicks anywhere else <code>defaultFunction()</code> is also executed. This might be
useful sometimes.</p>


<p>Setting document&#8211;wide event handlers is necessary in drag&#8211;and&#8211;drop
scripts. Typically a <code>mousedown</code> event on a layer selects this layer and makes
it respond to the <code>mousemove</code> event. Though the
<code>mousedown</code> is usually registered on the layer to avoid browser bugs, both
other event handlers must be document&#8211;wide.</p>

<p>Remember the First Law of Browserology: anything can happen, and it usually does when you&#8217;re
least prepared for it. So it may happen that the user moves his mouse very wildly and the
script doesn&#8217;t keep up so that the mouse is not over the layer any more.</p>

<ul>
<li>If the <code>onmousemove</code> event handler is registered to the layer,
the layer doesn&#8217;t react to the mouse movement any more, causing confusion.</li>

<li>If the <code>onmouseup</code> event handler is registered on the layer,
this event isn&#8217;t caught either so that the layer keeps reacting to the mouse
movements even after the user thinks he dropped the layer. This causes even more confusion.</li>
</ul>

<p>So in this case event bubbling is very useful because registering
your event handlers on document level makes sure they&#8217;re always executed.</p>

<h3>Turning it off</h3>

<p>But usually you want to turn all capturing and bubbling off to keep functions from
interfering with each other.
Besides, if your document structure is very complex (lots of nested tables and such) you may save system
resources by turning off bubbling. The browser has to go through every single ancestor element
of the event target to see if it has an event handler. Even if none are found, the search still takes time.</p>

<p>In the Microsoft model you must set the event&#8217;s <code>cancelBubble</code> property to true.</p>

<pre>
window.event.cancelBubble = true
</pre>

<p>In the W3C model you must call the event&#8217;s <code>stopPropagation()</code> method. </p>

<pre>
e.stopPropagation()
</pre>

<p>This stops all propagation of the event in the bubbling phase.
Stopping event propagation in the capturing phase is impossible. One wonders why.</p>

<p>For a complete cross-browser experience do</p>

<pre>
function doSomething(e)
{
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}
</pre>

<p class="smaller">Setting the <code>cancelBubble</code> property in browsers that don&#8217;t support it doesn&#8217;t hurt.
The browser shrugs and creates the property. Of course it doesn&#8217;t actually
cancel the bubbling, but the assignment itself is safe.</p>

<h3>currentTarget</h3>

<p>As we&#8217;ve seen earlier, an event has a <code>target</code> or <code>srcElement</code> that
contains a reference to the element the event happened on. In our example this is element2,
since the user clicked on it.</p>

<p>It is very important to understand that during the capturing and bubbling phases (if any)
this target does not change: it always remains a reference to element2.</p>

<p>But suppose we register these event handlers:</p>

<pre>
element1.onclick = doSomething;
element2.onclick = doSomething;
</pre>

<p>If the user clicks on element2 <code>doSomething()</code> is executed twice. But how
do you know which HTML element is currently handling the event? <code>target/srcElement</code>
don&#8217;t give a clue, they always refer to element2 since it is the original source of the
event.</p>

<p>To solve this problem W3C has added the <code>currentTarget</code> property. It contains a
reference to the HTML element the event is currently being handled by: exactly what we need.
Unfortunately the Microsoft model doesn&#8217;t contain a similar property.</p>

<p>You can also use
<a href="this.html">the <code>this</code> keyword</a>.
In the example above it refers to the HTML element the event is handled on, just like
<code>currentTarget</code>.</p>

<h3>Problems of the Microsoft model</h3>

<p>But when you use the Microsoft event registration model
the <code>this</code> keyword doesn&#8217;t refer to the HTML element. Combined with the
lack of a <code>currentTarget</code>&#8211;like property in the Microsoft model,
this means that if you do</p>

<pre>
element1.attachEvent('onclick',doSomething)
element2.attachEvent('onclick',doSomething)
</pre>

<p>you <em>cannot</em> know which HTML element currently handles the event. This is the most
serious problem with the Microsoft event registration model and for me it&#8217;s reason enough
never to use it, not even in IE/Win only applications.</p>

<p>I hope Microsoft will soon add a <code>currentTarget</code>&#8211;like property &#8212; or maybe
even follow the standard? Web developers need this information.</p>

<h3>Continue</h3>

<p>If you wish to go through all event pages in order, you should now continue with the
<a href="events_mouse.html">Mouse events</a> page.</p>

<div id="footer"><a href="/home.html">Home</a> <a href="/sitemap.html">Sitemap</a>
<p class="smaller" id="validation">Valid XHTML 1.0</p>
</div>
</body>
</html>
