[JavaScript] Events – Propagation

Understanding how events are propagated and when to add handlers is very important for web developers. Naive coding might result in unexpected behaviors that are hard to trace.

1. Event Propagation Models

There are 3 ways for the events to propagate:

  • Capturing : top-down
  • Bubbling : down-top
  • W3C model : Capturing -> Bubbling

All modern browsers support the W3C model; therefore you can attach the event handler either at the capturing phase or the bubbling phase.


2. Traditional Model (using “onclick”)

For all browsers, a traditional event registration attaches the handler to the bubbling phase.

document.getElementById("div1").onclick = onClick1;

function onClick1() { alert("1"); }
function onClick2() { alert("2"); }

The elements are nested.

<div id="div1" style="height:100px;background-color:Gray;">
  <input id="btn1" type="button" value="Click 1">

When the button is clicked, both elements respond to the click event.


3. Registering Events using “addEventListener()”

  • addEventListener(type, listener, bUseCapture)

The third parameter “bUseCapture” is a Boolean value to specify to which stage (capturing – ‘true’ or bubbling – ‘false’) the event is registered. It is very useful to control when the event is captured precisely.

document.getElementById("div1").addEventListener('click', onClick1, true);
document.getElementById("div2").addEventListener('click', onClick2, false);
document.getElementById("btn1").addEventListener('click', onClick3, true);

function onClick1() { alert("1"); }
function onClick2() { alert("2"); }
function onClick3() { alert("3"); }

The elements are also nested.

<div id="div1" style="height:300px;background-color:#ccc;">
  <div id="div2" style="height:200px;background-color:#999;">
    <input id="btn1" type="button" value="Click 1" />

When the button is clicked, message boxes will be popped up in this order “1” – “3” – “2”.

If you want to register all handlers in the bubbling phase, set the flag to “false” or omit it (the default is false).

[Note] The “addEventListener()” does not work in IE 8 and older. If you need to support IE 7 or IE 8, the alternative is the “attachEvent()” function. It always attaches the event to the “Bubbling” phase.


4. jQuery Event Handling

jQuery attaches events to the “bubbling” phase.

$(document).ready(function () {

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s