HTML DOM Event srcElement
: Testing Event Handlers
The HTML DOM srcElement
property is a crucial part of event handling in JavaScript. It provides a reference to the HTML element that triggered a specific event. This property is particularly useful for testing event handlers, identifying the source of events, and dynamically adjusting behavior based on the originating element. In this guide, we will delve into the details of the srcElement
property, demonstrate its usage, and highlight best practices for effective event handling.
What is the srcElement
Property?
The srcElement
property is an attribute of the Event object, which is passed as an argument to event handlers. It represents the element that dispatched the event. This is extremely useful because the same event listener can be attached to multiple elements, and within the event handler, you can use srcElement
to determine which element was clicked, hovered, or otherwise interacted with.
Purpose of the srcElement
Property
The main purpose of the srcElement
property is to:
- Identify the event source: Determine which element triggered the event.
- Test event handlers: Verify if the correct element is dispatching the event.
- Implement dynamic behavior: Adjust event handler logic based on the event target.
- Enhance event delegation: Efficiently handle events from multiple elements using a single handler on a parent element.
Syntax
The srcElement
property is read-only and is accessed through the Event object passed to an event handler.
event.srcElement;
Here, event
is the Event object passed to the event listener function.
Important Attributes of the Event Object related to srcElement
Understanding these attributes will give you a better picture of event handling and the role of srcElement
Attribute | Type | Description |
---|---|---|
`srcElement` | Object | Returns the HTML element that triggered the event (the source). This is often the element on which the event listener was attached or a child of it due to event bubbling. |
`target` | Object | Returns the HTML element that triggered the event. Similar to `srcElement` but more consistently supported across browsers and in modern event handling. It is the standard way to get event target. |
`currentTarget` | Object | Returns the HTML element to which the event listener is attached. Useful in cases of event delegation, where multiple elements may trigger the same handler. |
`type` | String | Returns the type of the event (e.g., “click”, “mouseover”). |
`timeStamp` | Number | Returns the number of milliseconds elapsed since the document loading began, when the event was triggered. |
`bubbles` | Boolean | Returns true if the event bubbles up the DOM tree, and false otherwise. |
Note: While srcElement
was widely used, modern standards recommend using target
instead due to its better compatibility and consistency across browsers. However, srcElement
is still supported, especially in older browsers. 💡
Examples of Using srcElement
Let’s explore practical examples that demonstrate how the srcElement
property can be used effectively. Each example includes the necessary HTML and JavaScript code.
Basic Click Event Handling
In this example, we use srcElement
to identify the button that was clicked and display its id
.
<button id="button1">Button 1</button>
<button id="button2">Button 2</button>
<p id="output1"></p>
<script>
const button1 = document.getElementById("button1");
const button2 = document.getElementById("button2");
const output1 = document.getElementById("output1");
function handleClick(event) {
output1.textContent = "Clicked on: " + event.srcElement.id;
}
button1.addEventListener("click", handleClick);
button2.addEventListener("click", handleClick);
</script>
Output:
Clicking “Button 1” displays: “Clicked on: button1”.
Clicking “Button 2” displays: “Clicked on: button2”.
Using srcElement
in Event Delegation
This example demonstrates how to use srcElement
to delegate events from multiple list items to a single handler attached to the parent ul
element.
<ul id="list1">
<li id="item1">Item 1</li>
<li id="item2">Item 2</li>
<li id="item3">Item 3</li>
</ul>
<p id="output2"></p>
<script>
const list1 = document.getElementById("list1");
const output2 = document.getElementById("output2");
list1.addEventListener("click", function (event) {
output2.textContent = "You clicked: " + event.srcElement.id;
});
</script>
Output:
Clicking “Item 1” displays: “You clicked: item1”.
Clicking “Item 2” displays: “You clicked: item2”.
Clicking “Item 3” displays: “You clicked: item3”.
Handling Mouseover Events
In this example, we use srcElement
to track which element the mouse is hovering over and dynamically change its style.
<div id="container1" style="display:flex; gap: 10px; border: 1px solid black; padding:10px;">
<div id="box1" style="width: 50px; height: 50px; background: lightblue;"></div>
<div id="box2" style="width: 50px; height: 50px; background: lightgreen;"></div>
</div>
<p id="output3"></p>
<script>
const container1 = document.getElementById("container1");
const output3 = document.getElementById("output3");
container1.addEventListener('mouseover', function(event){
event.srcElement.style.opacity = 0.5;
output3.textContent = "Mouse over: " + event.srcElement.id;
})
container1.addEventListener('mouseout', function(event){
event.srcElement.style.opacity = 1;
output3.textContent = "Mouse out: " + event.srcElement.id;
})
</script>
Output:
When the mouse hovers over “box1”, its opacity changes and the text “Mouse over: box1” is displayed. When it moves out, opacity goes back to 1 and “Mouse out: box1” is displayed.
Similarly, hovering and out from “box2” has the same effect.
Dynamic Content Modification
In this example, we use srcElement
to dynamically modify the content of an element when a button is clicked.
<div id="container2">
<p id="message">Click the button to change this text.</p>
<button id="changeText">Change Text</button>
</div>
<script>
const changeText = document.getElementById("changeText");
const message = document.getElementById("message");
changeText.addEventListener("click", function (event) {
message.textContent = "Text changed by button " + event.srcElement.id;
});
</script>
Output:
Initially, the paragraph shows “Click the button to change this text.”.
Clicking on “Change Text” button changes it to: “Text changed by button changeText”.
Comparing srcElement
to target
and currentTarget
While srcElement
can be used to identify the source of an event, it’s important to understand its relationship to other related properties:
target
: Returns the element that triggered the event, similar tosrcElement
. However,target
is the recommended and more consistent approach in modern JavaScript and cross browser compatibility. It is standard.currentTarget
: Returns the element on which the event listener is attached. Useful in event delegation, especially when the event bubbles up the DOM tree.
Here is an example showing the difference.
<div id="parentDiv" style="border: 1px solid black; padding: 10px;">
<button id="childButton">Click Me</button>
</div>
<p id="output4"></p>
<script>
const parentDiv = document.getElementById('parentDiv');
const childButton = document.getElementById('childButton');
const output4 = document.getElementById('output4');
parentDiv.addEventListener('click', function(event){
output4.innerHTML = `
srcElement: ${event.srcElement.id} <br>
target: ${event.target.id} <br>
currentTarget: ${event.currentTarget.id}
`;
})
</script>
Output:
When clicking the button, you’ll get output similar to:
srcElement: childButton
target: childButton
currentTarget: parentDiv
This shows how:
srcElement
andtarget
point to the originating element where event started (childButton
in this case).currentTarget
points to the element where the event listener was actually attached (parentDiv
).
Note: In most cases, target
and srcElement
will give the same result, but always prefer using target
for better cross-browser compatibility. Use currentTarget
to refer the actual element the event listener is attached to.
When to Use srcElement
- Legacy Code: When working with older codebases that rely on
srcElement
. - Specific Browser Compatibility: In cases where
srcElement
is preferred or required for browser compatibility reasons (usually older browsers). - Event Delegation: As a way to reference elements within the delegated event. Although
target
is preferred.
Best Practices
- Prefer
target
: Use thetarget
property for better consistency and compatibility. - Avoid Direct DOM Manipulation: Minimize direct manipulation of elements in event handlers, use class changes or attribute changes instead.
- Use Event Delegation: Employ event delegation for better performance, especially when handling events on numerous elements.
- Understand Event Bubbling: Be aware of how events bubble up the DOM tree when using
srcElement
ortarget
.
Browser Support
The srcElement
property is supported in all major browsers. However, the use of target
is recommended for modern development.
Note: While srcElement
is still widely supported, it’s essential to keep track of browser compatibility and choose the approach that works best for your needs. Always favor target
over srcElement
. ✅
Conclusion
The srcElement
property is a useful tool for understanding and testing event handlers in JavaScript. It provides a reference to the element that triggered an event, making it useful for a variety of applications, particularly event delegation. However, in modern development, target
should be preferred due to its better cross-browser support and standards compliance. This guide has shown you how to use srcElement
effectively and understand its place within the broader landscape of DOM event handling. By following these practices, you can create more robust and efficient event-driven web applications.