Home Page -> DOM Tutorials -> Using Events -> Setting Events -> Event Capture and Bubbling

Event Capture and Bubbling

The DOM has two ways for objects to detect events: from the top down, and from the bottom up. The first method is known as event capture, the second is called event bubbling.

Event Capture

diagram showing arrows moving downwards

Let's say that your document contains a <div> which contains a <p> which contains an <img>. Further, let's say you've added an event listener to all of them. When a user clicks on the image, a mouseclick event occurs.

Even though the user clicked the image, the image doesn't get the event first. Instead, the event listener attached to the document grabs the event first and processes it. (That is, it captures the event before it gets to its intended target.) The event is then passed down to the <div>'s event listener. The event then goes to the <p>, and finally to the <img>. That is, all of the clicked-on object's “ancestors” higher up in the document capture the event for processing before sending it down the chain to its intended target. You can try event capture in a pop-up window. (This only works in Mozilla.)

Event Bubbling

diagram showing arrows moving upwards

Now let's look at the same situation from the inside out. You have an <img> inside a <p>, which is inside a <div>, which is inside your document. When a user clicks the image, this time the events rise like a bubble in a glass of water. The click's original target, the <img>, gets to see the event first, and then passes it upwards to the <p> for further processing, which passes it on to the <div>, which finally passes it up to the document. You can try event bubbling in a pop-up window. (This only works in Mozilla.)

Here are the relevant parts of the source code for both demos.

 Setting Events