-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
A DOM Event Listener is a function in JavaScript that waits for an event to occur on a specific element and executes a callback when that event happens. Unlike inline event handlers (like onclick
), event listeners provide more flexibility, better separation of concerns, and the ability to attach multiple events to a single element.
Event listeners are central to making web pages interactive, responding to clicks, keyboard presses, mouse movements, and many other user or system actions.
Using event listeners has several advantages:
Separation of HTML and JavaScript – Keeps HTML clean without inline event handlers.
Multiple event handlers – You can attach more than one function to the same event on a single element.
Control and removal – You can remove event listeners when no longer needed, improving performance.
Advanced features – Supports options like capturing, bubbling, and passive events for fine control.
element.addEventListener(event, callback, options);
event
– The type of event, e.g., "click"
, "mouseover"
.
callback
– The function executed when the event occurs.
options
– Optional object controlling event behavior (capture, once, passive).
Example:
let btn = document.getElementById("myBtn");
// Add click event listener
btn.addEventListener("click", () => {
alert("Button clicked!"); // Action performed on click
});
Unlike inline handlers, you can attach multiple listeners to the same element:
let box = document.querySelector(".box");
// First listener
box.addEventListener("mouseover", () => {
box.style.backgroundColor = "blue"; // Change color on hover
});
// Second listener
box.addEventListener("mouseover", () => {
box.style.border = "2px solid black"; // Add border on hover
});
Both functions execute when the event occurs.
addEventListener
supports an options object to control behavior:
element.addEventListener("click", callback, {
capture: false, // Use capturing instead of bubbling
once: true, // Listener will be executed only once
passive: true // Improves scroll performance (cannot call preventDefault)
});
capture
– Executes during the capture phase instead of bubbling.
once
– Automatically removes the listener after it runs once.
passive
– Indicates listener will not call preventDefault()
, useful for scroll events.
Example:
let btn = document.getElementById("myBtn");
btn.addEventListener(
"click",
() => { alert("Clicked once!"); },
{ once: true } // Only runs one time
);
Event listeners can be removed using removeEventListener
. You must pass the same function reference:
function handleClick() {
alert("Button clicked!");
}
let btn = document.getElementById("myBtn");
// Add listener
btn.addEventListener("click", handleClick);
// Remove listener
btn.removeEventListener("click", handleClick);
Note: Anonymous functions cannot be removed, so always use named functions if removal is needed.
Feature | Inline Handler (onclick ) |
Event Listener (addEventListener ) |
---|---|---|
Multiple handlers | Only one per event | Multiple handlers allowed |
Separation of concerns | No (mixes HTML & JS) | Yes (keeps HTML clean) |
Removal | Difficult | Easy with removeEventListener |
Flexibility | Limited | Full control with options |
let btn = document.getElementById("myBtn");
btn.addEventListener("click", () => {
console.log("Button was clicked");
});
document.addEventListener("keydown", (event) => {
console.log("Pressed key:", event.key);
});
let box = document.querySelector(".box");
box.addEventListener("mouseover", () => {
box.style.backgroundColor = "yellow"; // Highlight on hover
});
box.addEventListener("mouseout", () => {
box.style.backgroundColor = "red"; // Revert color
});
let form = document.getElementById("signupForm");
form.addEventListener("submit", (event) => {
event.preventDefault(); // Prevent default form submission
alert("Form submitted successfully!");
});
Event delegation allows you to attach a listener to a parent element and catch events from its child elements. This is efficient for dynamic content.
let ul = document.getElementById("myList");
ul.addEventListener("click", (event) => {
if (event.target.tagName === "LI") {
alert("You clicked on: " + event.target.textContent);
}
});
Saves memory by attaching fewer listeners.
Works for dynamically added child elements.
<div id="buttonPanel">
<button>Button 1</button>
<button>Button 2</button>
<button>Button 3</button>
</div>
<div id="output"></div>
let panel = document.getElementById("buttonPanel");
let output = document.getElementById("output");
// Event delegation: listen for clicks on any button inside panel
panel.addEventListener("click", (event) => {
if (event.target.tagName === "BUTTON") {
output.textContent = "You clicked: " + event.target.textContent;
}
});
Dynamically handles all buttons inside the panel.
Works even if new buttons are added later.
Use addEventListener
over inline handlers.
Prefer named functions for adding/removing listeners.
Use event delegation for multiple similar elements.
Utilize options (once
, capture
, passive
) for better control.
Avoid attaching unnecessary listeners to improve performance.
DOM Event Listeners are a powerful tool in JavaScript for handling events dynamically. Key takeaways:
addEventListener
allows flexible, modular event handling.
Supports multiple handlers, options, and removal.
Can be used for mouse, keyboard, form, window, and custom events.
Event delegation is a memory-efficient approach for dynamic elements.
Mastering event listeners is essential for creating interactive, responsive, and maintainable web applications.
Add a click
event listener to a button that changes its background color when clicked.
Attach a mouseover
and mouseout
listener to a <div>
to highlight it on hover and revert on mouse out.
Add a keydown
event listener to log the key pressed by the user.
Attach a submit
event listener to a form to prevent default submission and display a message instead.
Use event delegation to handle clicks on <li>
items inside a <ul>
dynamically.
Add a resize
listener to the window to display the current width and height of the browser.
Attach a focus
and blur
listener to an input field to change its border color on focus and revert on blur.
Add a dblclick
listener to a paragraph that toggles its text color between two colors.
Add a once
listener to a button so that it only responds to the first click.
Use a listener on a parent container to log the text content of any dynamically added child element that is clicked.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts