Java Reference
In-Depth Information
console.log("Clicked on li");
});
Now try clicking on the first list item. There should be a message in the console saying
"Clicked on li" because this was the target element. The event then bubbles up to the parent
<ul > element and displays a message in the console saying "Clicked on ul". The event will
continue to bubble all the way to the root HTML element, but nothing will happen because
none of the other elements had event listeners attached to them.
Capturing
The addEventListener method has a third parameter, which is a Boolean value that
specifies whether capturing should be used or not. It defaults to false , which is why bub-
bling happens by default. There may be instances when you would rather capture the events
instead; for example, you might want events on outer elements to fire before any events
fire on the element that was actually clicked on.
To implement capturing instead, change the code to the following:
ul.addEventListener("click", function(event){
console.log("Clicked on ul");
},true);
li.addEventListener("click", function(event){
console.log("Clicked on li");
},true);
Now if you click on the first list item, "Clicked on ul" will be logged to the console first.
The events then propagate downwards to the child <li> element, so "Clicked on li" is
logged to the console next.
If you want the event to both capture and bubble, you must set a separate event handler for
both cases, like so:
// capturing
ul.addEventListener("click", function(event){
console.log("Clicked on ul");
Search WWH ::




Custom Search