Java Reference
In-Depth Information
Warning: Keep Bubbling
Be very wary of using the event.stopPropagation() method to stop
the bubble phase occurring. There may be other event listeners attached to
elements further up the bubble chain that won't be fired as a result.
Event Delegation
Event delegation can be used to attach an event listener to a parent element in order to
capture events that happen to its child elements.
Let's look at the list items in our example:
<ul id="list">
If we wanted to attach event listeners to all the <li> tags so that they were highlighted
when they were clicked on, it would need more code to add a separate event listener to each
element. In this case, it would only take a little more effort, but imagine if you had a 10 x
10 table with 100 elements!
A better way is to attach the event listener to the parent <ul> element and then use
the property to identify the element that was clicked on. Add the fol-
lowing to scripts.js to see this in action (remember that the highlight function used ):
Now clicking on any list item will highlight that list item as it was the target of the click
This is a useful method if you are adding extra list elements to the DOM dynamically. Any
new list elements that are a child of the <ul> element will automatically inherit this event
listener, saving you from having to add an event listener every time a new list item is ad-
Search WWH ::

Custom Search