JAVASCRIPT Tutorial

addEventListener Method

Overview

addEventListener is a method used to attach an event listener to an HTML element, allowing you to specify the type of event and the function to execute when the event occurs.

Key Concepts

  • addEventListener: The method used to attach the event listener.
  • Event Type: The specific event to listen for (e.g., "click", "keydown").
  • Callback Function: The function that will be executed when the event occurs.
  • HTML Element: The HTML element to which the listener will be attached.

Practical Steps

  1. Obtain the HTML element: Use JavaScript to select the element to which you want to attach the event listener.
  2. Define the event type: Specify the type of event you want to listen for (e.g., "click").
  3. Create a callback function: Write the function that will be called when the event occurs.
  4. Attach the event listener: Call the addEventListener method on the element, specifying the event type and the callback function.

Example

// Obtain the button element
const button = document.querySelector("button");

// Define the event type
const eventType = "click";

// Create a callback function
function handleClick() {
  alert("Button clicked!");
}

// Attach the event listener
button.addEventListener(eventType, handleClick);

In this example, when the button is clicked, the handleClick function will be executed.