JavaScript

JavaScript is a high-level, interpreted programming language that is widely used for web development. Initially designed as a client-side scripting language, it runs directly in web browsers, enabling dynamic and interactive user experiences. JavaScript can now be used for server-side development as well.

JavaScript HTML DOM EventListener

14 April 2025 | Category:

In modern JavaScript, the addEventListener() method is the most powerful and flexible way to handle events on HTML elements.

It allows you to:

  • Add multiple event handlers to a single element
  • Attach events without overwriting previous handlers
  • Control event flow (like bubbling and capturing)

🧠 What is addEventListener()?

The addEventListener() method attaches an event handler to an element without using inline HTML or overwriting other event handlers.

✅ Syntax:

element.addEventListener(event, function, useCapture);
  • event: A string like "click", "mouseover", "keydown", etc.
  • function: The callback function that runs when the event occurs.
  • useCapture (optional): Boolean value that controls event flow (default is false = bubbling).

🎯 Basic Example

<button id="btn">Click Me</button>

<script>
  const button = document.getElementById("btn");

  button.addEventListener("click", function () {
    alert("You clicked the button!");
  });
</script>

🟢 When you click the button, the alert pops up.
This is the most common use case for addEventListener().


🛠 Multiple Event Listeners on One Element

Unlike onclick, addEventListener() can attach more than one function to the same event:

button.addEventListener("click", () => {
  console.log("Event Handler 1");
});

button.addEventListener("click", () => {
  console.log("Event Handler 2");
});

🔁 Both functions will run when the button is clicked.


🧰 Named vs Anonymous Functions

You can pass a named function instead of an anonymous one:

function sayHello() {
  alert("Hello!");
}

button.addEventListener("click", sayHello);

Using named functions is useful when you want to remove the event listener later.


🔄 Removing Event Listeners

To remove an event listener, you use removeEventListener() with the same function reference:

button.removeEventListener("click", sayHello);

⚠ You cannot remove an anonymous function because it has no reference.


🎈 Example: Mouse Events

<div id="box" style="width: 100px; height: 100px; background: red;"></div>

<script>
  const box = document.getElementById("box");

  box.addEventListener("mouseover", () => {
    box.style.background = "green";
  });

  box.addEventListener("mouseout", () => {
    box.style.background = "red";
  });
</script>

👆 This changes the box color when you hover over it and resets it when the mouse leaves.


🎤 Listening to Keyboard Events

<input type="text" id="inputBox" placeholder="Type something..." />

<script>
  const inputBox = document.getElementById("inputBox");

  inputBox.addEventListener("keydown", (e) => {
    console.log("Key pressed:", e.key);
  });
</script>

⌨ This logs the key you press inside the input box.


🌐 Event Flow: Bubbling and Capturing

<div id="outer">
  <button id="inner">Click Me</button>
</div>

<script>
  document.getElementById("outer").addEventListener(
    "click",
    () => alert("Outer Div Clicked"),
    true // useCapture is true
  );

  document.getElementById("inner").addEventListener("click", () => {
    alert("Button Clicked");
  });
</script>
  • If useCapture is true, the outer div handles the event before the button (capturing phase).
  • If it’s false, the button handles it first (bubbling phase).

🧪 Common Events You Can Listen To

Event TypeDescription
"click"Element is clicked
"mouseover"Mouse hovers over element
"mouseout"Mouse leaves the element
"keydown"Key is pressed
"keyup"Key is released
"submit"Form is submitted
"change"Value of input changes
"load"Page or image fully loads
"scroll"Page or element is scrolled

💡 Why Use addEventListener()?

✅ Clean separation of HTML and JavaScript
✅ Can add multiple listeners
✅ Can control bubbling vs capturing
✅ More maintainable and readable code


🧾 Real World Example: Button Click Counter

<button id="countBtn">Click Me</button>
<p>You clicked <span id="count">0</span> times</p>

<script>
  let counter = 0;
  const countBtn = document.getElementById("countBtn");
  const countDisplay = document.getElementById("count");

  countBtn.addEventListener("click", () => {
    counter++;
    countDisplay.textContent = counter;
  });
</script>

📌 Summary

FeatureSupports
Add multiple handlers✅ Yes
Remove event listener easily✅ Yes
Capturing phase control✅ Yes
Inline use in HTML❌ No

✅ Conclusion

The addEventListener() method is a core concept in JavaScript for interacting with users. It gives you fine control over when, how, and where your JavaScript responds to events.