articles

home / developersection / articles / explain the html dom event methods in javascript

Explain the HTML DOM Event Methods in JavaScript

Explain the HTML DOM Event Methods in JavaScript

Ashutosh Kumar Verma 437 18-Mar-2025

HTML event methods in JavaScript allow us to handle user interactions such as button clicks, keypresses, mouse movements, etc. The HTML DOM provides various ways to add and manage event handlers in JavaScript.

 

Ways to attach event handlers

There are three common ways to attach events in JavaScript which are as given below,

Using the onclick Attribute (Inline Event Handler)

It is defined directly in the HTML element.

<button onclick="showMessage()">Click Me</button>
<script>
   function showMessage() {
       alert("Button Clicked!");
   }
</script>

Note: This is not recommended as it mixes HTML with JavaScript.

 

Using element.onclick (Property Event Handler)

It is defined in JavaScript.

<button id="btn">Click Me</button>
<script>
   document.getElementById("btn").onclick = function() {
       alert("Button Clicked!");
   };
</script>

Note: It has the limitation that one event handler can be assigned per event.

 

Using addEventListener() (Recommended)

It is the most flexible and preferred method.

<button id="btn">Click Me</button>
<script>
   document.getElementById("btn").addEventListener("click", function() {
       alert("Button Clicked!");
   });
</script>

Advantages of addEventListener()

  • Allows multiple event handlers for the same event.
  • Supports event propagation (capture and bubble phase).
  • Can dynamically remove event handlers.

 

Common Event Methods

Here are key event-related methods in JavaScript,

addEventListener(event, function, useCapture)

  • It attaches an event listener.
document.getElementById("btn").addEventListener("mouseover", function() {
   console.log("Mouse Hovered!");
});
  • useCapture (optional) controls the event flow (true for the capturing phase, false for the bubbling phase).

 

removeEventListener(event, function)

It removes an event listener.

function showMessage() {
   alert("Event Removed!");
}
document.getElementById("btn").addEventListener("click", showMessage);
document.getElementById("btn").removeEventListener("click", showMessage);

Note: The function reference must match exactly

 

event.preventDefault()

This prevents the default action of an element (for example, preventing form submission).

<a href="https://google.com" id="link">Click Me</a>
<script>
   document.getElementById("link").addEventListener("click", function(event) {
       event.preventDefault(); // Stops navigation
       alert("Default action prevented!");
   });
</script>

 

event.stopPropagation()

This prevents an event from being raised in the DOM.

<div id="outer">
   <button id="inner">Click Me</button>
</div>
<script>
   document.getElementById("outer").addEventListener("click", function() {
       alert("Outer Div Clicked!");
   });
   document.getElementById("inner").addEventListener("click", function(event) {
       alert("Button Clicked!");
       event.stopPropagation(); // Prevents event from reaching the outer div
   });
</script>

Note: Without stopPropagation() , clicking the button would trigger the event on the outer <div> as well.

 

Event Object Properties

When an event occurs, an event object (event) is automatically sent to the handler.

Example

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<title>Event Handling Example</title>
<style>
       .highlight { color: red; font-weight: bold; }
   </style>
</head>
<body>
<button id="btn">Click Me</button>
<script>

document.getElementById("btn").addEventListener("click", function(event) {
   console.log("Event Type:", event.type); // "click"
   console.log("Target Element:", event.target); // Button element
   console.log("Mouse X:", event.clientX, "Mouse Y:", event.clientY);
});
</script>
</body>
</html>

 

Event Delegation (Efficient Event Handling)

Instead of adding event listeners to multiple elements, delegate the event to a common parent.

Handling Multiple Buttons Efficiently

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<title>Event Handling Example</title>
<style>
       .highlight { color: red; font-weight: bold; }
   </style>
</head>
<body>
<div id="buttonContainer">
   <button class="btn">Button 1</button>
   <button class="btn">Button 2</button>
   <button class="btn">Button 3</button>
</div>
<script>
   document.getElementById("buttonContainer").addEventListener("click", function(event) {
       if (event.target.classList.contains("btn")) {
           alert(event.target.innerText + " Clicked!");
       }
   });
</script>
</body>
</html>

 

Advantages of Event Delegation

  • Improves performance by reducing event listeners.
  • Works dynamically for elements added later.

Common JavaScript Events

Event Description
click Fires when an element is clicked
dblclick Fires on a double-click
mouseover Fires when the mouse enters an element
mouseout Fires when the mouse leaves an element
keydown Fires when a key is pressed
keyup Fires when a key is released
submit Fires when a form is submitted
focus Fires when an input gains focus
blur Fires when an input loses focus
change Fires when input value changes (e.g., dropdown)
contextmenu Fires on right-click

 

Example

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Event Handling Example</title>
   <style>
       #box { width: 100px; height: 100px; background: gray; text-align: center; line-height: 100px; }
   </style>
</head>
<body>
   <div id="box">Hover Me</div>
   <button id="toggleBtn">Toggle Event</button>
   <script>
       let box = document.getElementById("box");
       function changeColor() {
           box.style.backgroundColor = "blue";
       }
       box.addEventListener("mouseover", changeColor);
       document.getElementById("toggleBtn").addEventListener("click", function() {
           if (box.style.backgroundColor === "blue") {
               box.removeEventListener("mouseover", changeColor);
               box.style.backgroundColor = "gray";
           } else {
               box.addEventListener("mouseover", changeColor);
           }
       });
   </script>
</body>
</html>

 

I hope you understand clearly.

Thanks!

 

Also, Read: Explain the HTML DOM Style Object in JavaScript


Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By