Monday, April 15, 2013

A Quick Look at and e.currentTarget. And Bubbling.

Since jQuery makes such easy work of event listeners it's sometimes easy to ignore some of the finer points of JavaScripts events.  Two things that I often forget is the difference between the and e.currentTarget properties of the event object that gets passed into a event callback. Hopefully writing this post will help the concepts stick in my head.

The reason we need both of these properties is because of event bubbling.  Event bubbling is when a event travels up the DOM, until it reaches the document node.   Lets say we have a DOM tree that looks like this:

|  |
|  |--span
|  |  |
|  |  |--a

Here we have a document node with a child of a div with a child of a span with a child of an anchor.  When the anchor is clicked the any event listeners for the anchor are triggered, then the event bubbles up to it's parent, the span and any of it's event listeners are triggered, then the event bubbles up to the div where its event listeners are triggered, and finally the event bubbles up to the document element where any  of it's event listeners are triggered.

Assuming that the span and div have a margin, padding, and border of 0 whenever a user clicks on the link the event the target property of the event that is triggered on the anchorspan,  div  and document will always be the anchor, since this is where the event originated. The currentTarget property will always be the element that is listening for the event.

The following code shows event listeners on 4 different objects, however when a user clicks on the anchor link the target will be the same for each event listener.

Open up your console and run the following example, paying close attention to the order the events fire as they bubble up the dom:

JS Bin
Fork me on GitHub