← Back to Chapters

JavaScript DOM Events

?️ JavaScript DOM Events

? Quick Overview

JavaScript DOM events are actions or occurrences that happen in the browser, such as mouse clicks, keyboard presses, form submissions, page loads, and more. JavaScript lets you listen to these events and run functions in response, making your web pages interactive and dynamic.

? Key Concepts

  • Event: Any interaction like click, key press, mouse movement, form submit, or page load.
  • Event handler / listener: A function that runs when a specific event occurs.
  • Inline events: Using attributes like onclick directly in HTML tags.
  • addEventListener(): Modern, flexible way to attach one or more handlers to an element.
  • Mouse & keyboard events: Help detect user activity via cursor and keys.
  • Form events: Used for validation before data is sent to the server.
  • Event object: Contains details like event type, target element, and more.
  • Event bubbling & capturing: How events travel through the DOM tree.

? Syntax and Patterns

? Inline Event Attributes

You can attach events directly in HTML using attributes like onclick, onmouseover, onsubmit, etc. This is simple but can become hard to manage in large projects.

? DOM Properties as Handlers

Another way is to select an element in JavaScript and assign a function to a property like element.onclick or element.onmouseover. Each property can hold only one handler.

➕ addEventListener()

The preferred modern way is element.addEventListener(eventType, handler, useCapture). It allows multiple handlers for the same event and can control whether the handler runs in capturing or bubbling phase.

? Code Examples

?️ Basic onclick Event

The onclick event is triggered when a user clicks an element. Here a button updates the text of a paragraph.

? View Code Example
// Button that triggers the showMessage() function when clicked
<button onclick="showMessage()">Click Me</button>
// Empty paragraph where the message will be displayed
<p id="demo"></p>

// Script block containing the event handler function
<script>
function showMessage() {
  // Find the paragraph and change its text when the button is clicked
  document.getElementById("demo").innerText = "Button clicked!";
}
</script>

? Multiple Handlers with addEventListener()

With addEventListener(), you can attach several handlers to the same event on one element without overwriting existing listeners.

? View Code Example
// Button that will have multiple click handlers attached
<button id="multiBtn">Multi Handler</button>

// Script that demonstrates multiple event listeners on the same button
<script>
const btn = document.getElementById("multiBtn");

// First click handler: shows an alert
btn.addEventListener("click", function() {
  alert("Handler 1 triggered!");
});

// Second click handler: logs a message to the console
btn.addEventListener("click", function() {
  console.log("Handler 2 also triggered!");
});
</script>

? Mouse Events

Mouse events include clicks, hovering, entering, leaving, and pressing/releasing mouse buttons. Below, a box changes color when the mouse enters and leaves.

  • onclick – mouse clicks an element
  • onmouseover – mouse pointer enters an element
  • onmouseout – mouse pointer leaves an element
  • onmousedown / onmouseup – mouse button pressed / released
? View Code Example
// A simple square div that will react to mouse hover
<div id="hoverBox" style="width:100px;height:100px;background:red;"></div>

// Script to change the color of the box on mouse events
<script>
const hoverBox = document.getElementById("hoverBox");

// When the mouse enters the box, change the background to blue
hoverBox.onmouseover = () => {
  hoverBox.style.background = "blue";
};

// When the mouse leaves the box, change the background back to red
hoverBox.onmouseout = () => {
  hoverBox.style.background = "red";
};
</script>

⌨️ Keyboard Events

Keyboard events such as keydown, keyup, and keypress help detect which key the user is pressing.

? View Code Example
// Text input that calls detectKey(event) on every keydown
<input
  type="text"
  id="textInput"
  onkeydown="detectKey(event)"
  placeholder="Type something"
/>

// Script that logs which key the user pressed
<script>
function detectKey(event) {
  // event.key contains the character or key name that was pressed
  console.log("Key pressed:", event.key);
}
</script>

? Form Validation with onsubmit

The onsubmit event is commonly used to validate forms before sending data to the server. Returning false (or using event.preventDefault()) stops the form from submitting.

? View Code Example
// Simple form that calls validateForm() when submitted
<form onsubmit="return validateForm()">
  // Text input where the user must enter a name
  <input type="text" id="name" placeholder="Enter name">
  // Submit button to send the form
  <input type="submit" value="Submit">
</form>

// Script to validate the form before allowing submission
<script>
function validateForm() {
  const name = document.getElementById("name").value;

  // If the name field is empty, show an alert and stop the form submission
  if (name === "") {
    alert("Name is required!");
    return false; // stop submission
  }
}
</script>

? Window onload Event

The onload event ensures that your script runs only after the entire page (including images and other resources) has finished loading.

? View Code Example
// Script that waits for the window to finish loading
<script>
window.onload = function() {
  // This code runs only after all page resources are fully loaded
  console.log("The page has fully loaded.");
};
</script>

? Using the Event Object

Every event handler receives an event object that holds useful information such as the event type, target element, and more.

? View Code Example
// Button that passes the event object to the handler
<button onclick="handleEvent(event)">Event Info</button>

// Script that shows information from the event object
<script>
function handleEvent(e) {
  // e.type is the event type, e.target is the element that triggered the event
  alert(
    "Type: " + e.type +
    "\nTarget: " + e.target.tagName
  );
}
</script>

? Event Bubbling and Capturing

Events in the DOM go through two main phases: capturing (from the window down to the target) and bubbling (from the target back up to the window).

In the example below, clicking the button will trigger the button's handler first, then the surrounding div's handler (bubbling).

? View Code Example
// Outer div with a click handler
<div
  onclick="alert('DIV clicked')"
  style="padding:30px;background:#ddd;"
>
  // Inner button with its own click handler
  <button onclick="alert('BUTTON clicked')">Click</button>
</div>

? Interactive Example

Try this mini demo: click the button to change the message and type in the input to see which key you press.

? Live Demo

Waiting for a click...

Key info will appear here.

? Live Output & Explanation

When you click the demo button, a click event is fired on that button. The attached event handler updates the paragraph text to show that the button was clicked.

When you type in the input, each key press triggers a keydown event. The handler reads event.key to identify which key you pressed and displays it on the screen.

This is exactly how real web pages react to user actions: they listen for DOM events and modify the page or perform logic in response.

? Tips & Best Practices

  • Prefer addEventListener() over inline onclick for flexibility and cleaner HTML.
  • Use event.preventDefault() to stop default actions (like form submission or link navigation) when needed.
  • Use event.target to know exactly which element triggered the event.
  • Attach events in window.onload or DOMContentLoaded so the DOM is ready.
  • Keep handler functions small and reusable instead of writing complex inline code.

? Try It Yourself

  • Create a button that changes text using onclick.
  • Detect and display which key the user presses in an input field.
  • Use addEventListener to assign multiple actions to one element.
  • Prevent a form from submitting if the input is empty.
  • Use mouseover and mouseout to animate color changes.
  • Log the event object’s type and target on a click.
  • Demonstrate event bubbling by nesting two elements with click handlers.