JavaScript DOM Events

Events are at the core of interactive web applications, allowing developers to respond to user actions such as clicks, key presses, and mouse movements.

The Document Object Model (DOM) in JavaScript provides a robust event-handling mechanism that enables developers to create dynamic, responsive user interfaces.

This chapter will delves into the fundamentals of DOM events in JavaScript, exploring how to listen for events, handle them, and use advanced techniques for managing event-driven behavior.

Understanding DOM Events

DOM events represent actions that occur in the browser, such as user interactions, browser actions, or other occurrences.

Each event has an associated event object that provides information about the event. Events can be categorized into several types, including mouse events, keyboard events, form events, and more.

// Example of a basic event listener
document.addEventListener("DOMContentLoaded", (event) => {
  console.log("The DOM is fully loaded"); 
})

The above example with log the out when the window is loaded.

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <script>
      document.addEventListener("DOMContentLoaded", (event) => {
        console.log("The DOM is fully loaded"); 
      })
    </script>
  </body>
</html>

Event Listeners

Event listeners are functions that execute in response to an event.

They are attached to DOM elements using methods such as addEventListener(), which takes the event type and the listener function as arguments.

Event listeners provide a flexible way to handle multiple events on a single element.

// Adding an event listener
const button = document.getElementById("myButton");

button.addEventListener("click", () => {
  console.log("Button clicked!"); 
})

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <button id="myButton">Click Me!</button>
    <script>
      const button = document.getElementById("myButton");

      button.addEventListener("click", () => {
        console.log("Button clicked!"); 
      })
    </script>
  </body>
</html>

Event Object

The event object provides valuable information about the event, such as the type of event, the target element, and additional properties specific to the event type.

This object is automatically passed to the event handler function.

// Using the event object
const button = document.getElementById("myButton");

button.addEventListener("click", () => {
  console.log("Event type: ", event.type); // Logs 'click'
  console.log("Target element: ", event.target); // Logs the button element
})

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <button id="myButton">Click Me!</button>
    <script>
      const button = document.getElementById("myButton");

      button.addEventListener("click", () => {
        console.log("Event type: ", event.type); // Logs 'click'
        console.log("Target element: ", event.target); // Logs the button element
      });
    </script>
  </body>
</html>

Event Propagation

Event propagation describes how events travel through the DOM tree.

There are three phases: capturing, target, and bubbling.

By default, events bubble up from the target element to the root, but you can also capture events as they trickle down from the root to the target.

// Event propagation example
const outerDiv = document.getElementById("outerDiv");
const innerDiv = document.getElementById("innerDiv");

outerDiv.addEventListener("click", () => {
  console.log("Outer DIV clicked");
})

innerDiv.addEventListener("click", () => {
  console.log("Inner DIV clicked");
  event.stopPropagation(); // Stops the event from bubbling up
})

In the above example, when the innerDiv is clicked, both the innerDiv and outerDiv would receive the click event if event bubbling is not stopped.

This means that without event.stopPropagation(), clicking the innerDiv would log both "Inner DIV clicked" and "Outer DIV clicked".

We correctly used event.stopPropagation() in the innerDiv's click event handler, which prevents the click event from propagating (bubbling up) to the outerDiv.

As a result, only "Inner DIV clicked" is logged when innerDiv is clicked.

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <div id="outerDiv">
      <div id="innerDiv"></div>
    </div>
    <script>
      const outerDiv = document.getElementById("outerDiv");
      const innerDiv = document.getElementById("innerDiv");
      
      outerDiv.addEventListener("click", () => {
        console.log("Outer DIV clicked");
      })
      
      innerDiv.addEventListener("click", () => {
        console.log("Inner DIV clicked");
        event.stopPropagation(); // Stops the event from bubbling up
      })
    </script>
  </body>
</html>

Preventing Default Behavior

Some events have default behaviors (e.g., submitting a form, clicking a link).

The preventDefault()method can be used to prevent these default actions, allowing custom handling instead.

// Preventing default behavior
const link = document.getElementById("myLink");

link.addEventListener("click", () => {
  event.preventDefault(); // Prevents the default link click behavior
  console.log("Link click prevented");
})

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <a href="www.codingkoleji.com" id="myLink" alt="Visit my Website">Visit my Site</a>
    <script>
      const link = document.getElementById("myLink");

      link.addEventListener("click", () => {
        event.preventDefault(); // Prevents the default link click behavior
        console.log("Link click prevented");
      })
    </script>
  </body>
</html>

Delegating Events

Event delegation leverages event bubbling to manage events for multiple elements efficiently.

Instead of adding individual listeners to each element, a single listener is added to a common ancestor, which handles events from its descendants.

// Event delegation example
const list = document.querySelectorAll("li");

list.forEach(item => {
  item.addEventListener("click", () => {
    if (event.target.tagName === "LI"){ 
      console.log("List item clicked: ", event.target.textContent);
    }
  })
})

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <ul id="myList">
      <li>Banana</li>
      <li>Apple</li>
      <li>Guava</li>
      <li>Orange</li>
    </ul>
    <script>
      const list = document.querySelectorAll("li");

      list.forEach(item => {
        item.addEventListener("click", () => {
          if (event.target.tagName === "LI"){ 
            console.log("List item clicked: ", event.target.textContent);
          }
        })
      })
    </script>
  </body>
</html>

Handling Keyboard Events

Keyboard events are essential for responding to user input via the keyboard.

The keydown, keypress, and keyupevents can be used to detect when keys are pressed and released.

// Handling keyboard events
document.addEventListener("keydown", (event) => {
    console.log("Key pressed: ", event.key); // Logs the key that was pressed
})

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <script>
      document.addEventListener("keydown", (event) => {
        console.log("Key pressed: ", event.key); // Logs the key that was pressed
      })
    </script>
  </body>
</html>

Debouncing and Throttling

Debouncing and throttling are techniques to control the frequency of event handler execution, improving performance and user experience, especially for events that fire frequently (e.g., scroll, resize).

// Debouncing example
function debounce(func, delay){ 
  let timeoutId;
  return function(...args){
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => func.apply(this, args), delay);
  };
}

let handleResize = debounce(() => {
  console.log("Window resized");
}, 300);

window.addEventListener("resize", handleResize);

Example

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Title of the Document</title>
  </head>
  <body>
    <h1 id="heading">Welcome to CodingKoleji</h1>
    <script>
      function debounce(func, delay){ 
        let timeoutId;
        return function(...args){
          clearTimeout(timeoutId)
          timeoutId = setTimeout(() => func.apply(this, args), delay);
        };
      }
      
      let handleResize = debounce(() => {
        console.log("Window resized");
      }, 300);
      
      window.addEventListener("resize", handleResize);
    </script>
  </body>
</html>

Understanding and effectively using DOM events in JavaScript is crucial for creating interactive and responsive web applications.

These skills are fundamental to enhancing user interactions and ensuring smooth, dynamic experiences on modern web pages.

Here are some useful events that you should know:

Event Type Description
Mouse Events
click Fired when a mouse button is clicked on an element.
dblclick Fired when a mouse button is double-clicked on an element.
mousedown Fired when a mouse button is pressed down on an element.
mouseup Fired when a mouse button is released over an element.
mousemove Fired when the mouse pointer is moved over an element.
mouseover Fired when the mouse pointer is moved onto an element.
mouseout Fired when the mouse pointer is moved out of an element.
mouseenter Fired when the mouse pointer is moved onto an element (does not bubble).
mouseleave Fired when the mouse pointer is moved out of an element (does not bubble).
Keyboard Events
keydown Fired when a key is pressed down.
keypress Fired when a key is pressed and held down.
keyup Fired when a key is released.
Focus Events
focus Fired when an element gains focus.
blur Fired when an element loses focus.
Form Events
input Fired when the value of an element changes.
change Fired when the value of an element changes and the element loses focus.
submit Fired when a form is submitted.
reset Fired when a form is reset.
Clipboard Events
copy Fired when content is copied.
cut Fired when content is cut.
paste Fired when content is pasted.
Drag Events
drag Fired when an element is being dragged.
dragend Fired when the user has finished dragging the element.
dragenter Fired when the dragged element enters a valid drop target.
dragexit Fired when the dragged element leaves a valid drop target.
dragleave Fired when the dragged element leaves a valid drop target.
dragover Fired when the dragged element is over a valid drop target.
dragstart Fired when the user starts dragging an element.
drop Fired when the dragged element is dropped on a valid drop target.
Misc Events
contextmenu Fired when the right mouse button is clicked (before the context menu is displayed).
scroll Fired when an element's scrollbar is being scrolled.
resize Fired when the document view is resized.
error Fired when an error occurs.
load Fired when an element has finished loading.
unload Fired when the document or a dependent resource is being unloaded.
abort Fired when the loading of a resource is aborted.
select Fired when some text is being selected.
wheel Fired when the mouse wheel or similar device is rotated.

Event though this is just an Introduction to the even you can deelve dive in to it by look for another material online or youtube videos. Let's learn about DOM forms in the next chapter.