This content originally appeared on DEV Community and was authored by Aman kumar
Sample HTML Structure
Let’s start with a simple HTML page that includes a list of images:
<ul id="images">
<li><img id="owl" src="owl.jpg" /></li>
<li><a id="google" href="https://google.com">Google</a></li>
</ul>
3 Ways to Handle Click Events
1. Inline HTML (Not Recommended)
<img onclick="alert('Owl')" />
Not a clean or scalable approach.
2. Using onclick
Property (Old Way)
document.getElementById('owl').onclick = function () {
alert('Owl');
};
Works, but limits flexibility (e.g., you can’t attach multiple listeners).
3.
Modern Way: addEventListener()
document.getElementById('owl').addEventListener('click', function () {
alert('Owl');
});
This is the preferred method. It allows multiple listeners, better control, and more modern event handling features.
The Event Object
document.getElementById('owl').addEventListener('click', function (e) {
console.log(e);
});
This logs the PointerEvent object, which gives you rich information like:
-
type
– what kind of event occurred -
target
,srcElement
,currentTarget
- Mouse positions:
clientX
,clientY
,screenX
,screenY
- Modifier keys:
altKey
,ctrlKey
,shiftKey
-
timestamp
,keyCode
(for keyboard events)
Event Propagation
Bubbling (default):
Events bubble from the target element upward to its ancestors.
document.getElementById('images').addEventListener('click', function () {
console.log('Clicked inside ul');
}, false);
document.getElementById('owl').addEventListener('click', function () {
console.log('Clicked on owl');
}, false);
Capturing:
Events flow top-down before reaching the target.
document.getElementById('images').addEventListener('click', function () {
console.log('Captured on ul');
}, true);
Stop Bubbling:
document.getElementById('owl').addEventListener('click', function (e) {
e.stopPropagation();
console.log('Clicked on owl');
});
![]()
stopPropagation()
prevents the event from reaching ancestor elements.
Preventing Default Behavior
Stop anchor tags from navigating:
document.getElementById('google').addEventListener('click', function (e) {
e.preventDefault();
console.log("Google link clicked, but not redirected.");
});
Bonus: Remove Image on Click
Let’s say you want to remove an image when it’s clicked. Here’s how:
document.querySelector('#images').addEventListener('click', function (e) {
if (e.target.tagName === 'IMG') {
let removeIt = e.target.parentNode;
removeIt.remove(); // Removes the <li> along with the image
}
});
This approach uses event delegation and works even if you add new images dynamically!
Summary
Feature | Description |
---|---|
addEventListener() |
Attach events cleanly |
e.target |
Element that triggered the event |
stopPropagation() |
Stops bubbling up the DOM |
preventDefault() |
Cancels default browser behavior |
Event Delegation | Handle multiple similar events efficiently |
This content originally appeared on DEV Community and was authored by Aman kumar