Last Updated : 28 Jul, 2025
The addEventListener() method is used to attach an event handler to an element in the DOM (Document Object Model). It listens for specific events (such as click, keydown, or submit) on that element and executes a function when the event occurs.
Syntax
element.addEventListener(event, function, useCapture);
element
: The DOM element you want to listen for events on (for example, document
, button
, div
).event
: The type of event you want to listen for, such as 'click'
, 'keydown'
, 'submit'
, etc.function
: The function to be executed when the event is triggered. It could be an anonymous function or a reference to a named function.useCapture
(optional): A boolean value that specifies whether to use event capturing. When you use addEventListener(), you’re essentially telling JavaScript to "watch" for a specific event on an element. Here's how it works:
Note => The event listener continuously checks for the occurrence of the specified event, and once it happens, the corresponding function is executed.
Now let's understand this with the help of example:
HTML
<html>
<head>
<title>JavaScript addEventListeners</title>
</head>
<body>
<button id="try">Click here</button>
<h1 id="text"></h1>
<script>
document.getElementById("try").addEventListener("click", function () {
document.getElementById("text").innerText = "GeeksforGeeks";
});
</script>
</body>
</html>
Output
JavaScript addEventListener() with ExamplesIn this example
In JavaScript, we can attach multiple event listeners to the same element. Each event listener can handle a different event or the same event type, and they will all trigger their respective functions when the event occurs.
Let's understand this with the help of example
HTML
<html>
<head>
<title>Multiple Event Listeners Example</title>
<style>
body {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f0f0f0;
font-family: Arial, sans-serif;
}
#myButton {
padding: 15px 30px;
font-size: 16px;
cursor: pointer;
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
transition: background-color 0.3s ease;
}
#myButton:hover {
background-color: #45a049;
}
#message {
font-size: 20px;
font-weight: bold;
margin-top: 20px;
}
</style>
</head>
<body>
<div>
<button id="myButton">Click me!</button>
<h1 id="message"></h1>
</div>
<script>
const button = document.getElementById("myButton");
const message = document.getElementById("message");
button.addEventListener("click", function () {
button.style.backgroundColor = "lightblue";
message.innerText = "Button was clicked!";
});
button.addEventListener("mouseenter", function () {
message.innerText = "Mouse is over the button!";
});
button.addEventListener("mouseleave", function () {
message.innerText = "Mouse left the button!";
});
document.addEventListener("keydown", function (event) {
if (event.key === "Enter") {
message.style.color = "green";
message.innerText = "Enter key pressed!";
}
});
</script>
</body>
</html>
Output
JavaScript addEventListener()In this example
The window object in JavaScript represents the browser window and can be used to listen for events that occur globally across the entire window, such as resizing the window, scrolling, or keypresses.
HTML
<html>
<head>
<title>Interactive Window Event Handlers</title>
<style>
body {
font-family: Arial, sans-serif;
text-align: center;
margin: 0;
padding: 20px;
height: 2000px;
transition: background-color 0.3s ease;
}
#message {
font-size: 20px;
font-weight: bold;
margin-top: 20px;
padding: 10px;
}
#keyPressDisplay {
font-size: 24px;
font-weight: bold;
margin-top: 30px;
color: #333;
}
</style>
</head>
<body>
<h1>Interact with the Page!</h1>
<div id="message">Resize the window, scroll down, or press a key!</div>
<div id="keyPressDisplay"></div>
<script>
const message = document.getElementById('message');
const keyPressDisplay = document.getElementById('keyPressDisplay');
// Window Resize Event
window.addEventListener('resize', function () {
const width = window.innerWidth;
const height = window.innerHeight;
message.innerText = `Window resized! New dimensions: ${width}x${height}`;
message.style.fontSize = (width / 50) + 'px';
});
window.addEventListener('scroll', function () {
const scrollY = window.scrollY;
document.body.style.backgroundColor = `rgb(${scrollY % 255}, ${255 - (scrollY % 255)}, 150)`;
message.innerText = `You have scrolled! Scroll position: ${scrollY}px`;
});
// Window Keydown Event
window.addEventListener('keydown', function (event) {
keyPressDisplay.innerText = `You pressed the "${event.key}" key!`;
if (event.key === 'Enter') {
keyPressDisplay.style.color = 'green';
} else if (event.key === 'Escape') {
keyPressDisplay.style.color = 'red';
} else {
keyPressDisplay.style.color = '#333';
}
});
</script>
</body>
</html>
Output
In this example
Event propagation refers to the way events "bubble" up or "capture" down the DOM tree. In the HTML DOM, there are two primary ways an event can propagate when it occurs: Event Bubbling and Event Capturing. These concepts determine the order in which events are handled when an event is triggered on nested elements.
Event BubblingIn Event Bubbling, the event starts from the innermost element (the target element) and bubbles up to the outer elements. This means that if you click on an element inside a parent element, the innermost element's event handler is triggered first, followed by the outer elements' handlers.
Event CapturingIn Event Capturing, the event starts from the outermost element (usually the document or window) and captures down to the target element. In this case, the outermost element's event handler is triggered first, and the event then "trickles down" to the inner elements.
Now let's understand this with the help of example
HTML
<html>
<head>
<title>Event Bubbling vs Capturing</title>
<style>
#parent {
background-color: lightblue;
padding: 20px;
margin: 20px;
}
#child {
background-color: lightgreen;
padding: 20px;
margin: 20px;
}
</style>
</head>
<body>
<div id="parent">
<p id="child">Click me!</p>
</div>
<script>
const parent = document.getElementById('parent');
const child = document.getElementById('child');
parent.addEventListener('click', function () {
alert('Parent Div Clicked (Capturing)');
}, true);
child.addEventListener('click', function () {
alert('Child Div Clicked (Bubbling)');
});
</script>
</body>
</html>
Output
In this example
RemoveEventListener() methodNote => By specifying true for the useCapture parameter, we can handle the event in the capturing phase rather than the bubbling phase. This gives you control over how events are managed in nested elements.
To remove an event listener in JavaScript, we can use the removeEventListener() method. This method allows us to remove an event listener that was previously added with addEventListener(). It requires the same arguments as addEventListener(), including the event type, the callback function, and the useCapture flag.
HTML
<html>
<head>
<title>Remove Event Listener Example</title>
<style>
#myButton {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: lightcoral;
color: white;
border: none;
border-radius: 5px;
}
</style>
</head>
<body>
<button id="myButton">Click me (3 times)</button>
<p id="message">You have clicked the button 0 times.</p>
<script>
const button = document.getElementById('myButton');
const message = document.getElementById('message');
let clickCount = 0;
function handleClick() {
clickCount++;
message.innerText = `You have clicked the button ${clickCount} times.`;
if (clickCount === 3) {
button.removeEventListener('click', handleClick);
message.innerText = 'You clicked the button 3 times. Event listener removed!';
}
}
button.addEventListener('click', handleClick);
</script>
</body>
</html>
Output
JavaScript addEventListener()In this example
Below are the some best practices which we need to follow when use event listner:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4