Every object in the DOM can trigger events, such as a button click or a mouse hover. The specific object that triggers an event is referred to as the target. The event.target
property provides a reference to the exact element where the event occurred, enabling us to create flexible and dynamic event handlers.
In the example above, the p
element is the target for both the mouseover
and mouseout
events. By using event.target
, the event handler dynamically applies the color change to the specific element that triggered the event.
Why use event.target
?
In situations where elements are added or removed from the DOM, event.target
makes sure that the event listener works seamlessly without needing to reassign or recreate listeners. For example, in a dynamically generated list, you can target newly added items without additional setup.
When using event.target
, a single event listener can handle multiple elements. This reduces redundancy, making your code more maintainable. This is particularly useful in cases like event delegation, about which you will learn in an upcoming lesson.
In the below example, a separate event listener is assigned to each li
element. When a new item Item 4 is added dynamically, it does not inherit the event listeners. Clicking on Item 4 does nothing unless a new listener is added manually.
By using event.target
, a single event listener manages all list items efficiently.
Here only one event listener is assigned to the parent <ul>
element. The event.target
property dynamically identifies the specific <li>
element that was clicked. When Item 4 is added dynamically, it is handled by the existing event listener attached to the parent <ul>
element. This works because event.target
pinpoints the exact element where the event originated, allowing us to verify and respond to the event dynamically without the need to attach new listeners for each added element.