A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript-addeventlistener-with-examples/ below:

JavaScript addEventListener() with Examples - GeeksforGeeks

JavaScript addEventListener() with Examples

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);
How addEventListener() Works?

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 Examples

In this example

Adding Multiple Event Listeners to an Element

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

Adding Event Handlers to the window Object

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

Understanding Event Propagation

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 Bubbling

In 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 Capturing

In 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

Note => 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.

RemoveEventListener() method

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

Why Use addEventListener()? Best Practices

Below are the some best practices which we need to follow when use event listner:


JavaScript Event Listener [Part -1] JavaScript Event Listener [Part -2] JavaScript Event Listener [Part -3]

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