16.5 Event Listeners and DOM Events (15 mins)

  1. Introduction to Event Listeners and DOM Events:

    • Events in JavaScript are actions that happen when the user interacts with a webpage (e.g., clicking a button, moving the mouse, pressing a key, resizing or closing the browser window, submitting a form, error occurrence, mouse hovering, video playing, pausing, and ending).

    • Event listeners are methods that allow JavaScript to "listen" for these user interactions and respond by executing specific functions.

    • Common DOM events include:

      • click: Triggered when the user clicks on an element.

      • mouseover: Triggered when the user hovers the mouse over an element.

      • keydown: Triggered when the user presses a key on the keyboard.

      • focus and blur : The focus event occurs when an element gains focus, while the blur event occurs when an element loses focus

  2. The addEventListener() Method:

    • addEventListener() attaches an event handler to a specific element, without overwriting other event handlers.

    • Syntax:

      element.addEventListener(event, function, useCapture);
      • event: The type of event (e.g., "click", "mouseover", "keydown").

      • function: The function to be executed when the event occurs.

      • useCapture: Optional, specifies the event flow phase (default is false for the bubbling phase).

  3. The removeEventListener() Method:

    • addEventListener() detaches an event handler added to an event handler using addEventListener()

    • Syntax:

      • element.removeEventListener(event, function, useCapture);
      • Explanation:

        1. element: The element on which the event listener is attached.

        2. event: The type of event to listen for (e.g., 'click', 'mouseover', 'keydown').

        3. function: The function that will be executed when the event occurs.

        4. useCapture: An optional boolean value indicating whether the event should be captured. Typically, false is used.

  4. Common DOM Events:

    • click event: Executes a function when an element is clicked.

      • Example:

        let button = document.getElementById("myButton");
        button.addEventListener("click", () => {
          console.log("Button clicked!");
        });
    • mouseover event: Triggers a function when the mouse pointer hovers over an element.

      • Example:

        let image = document.getElementById("myImage");
        image.addEventListener("mouseover", () => {
          image.style.border = "2px solid red";
        });
    • keydown event: Executes a function when a key is pressed on the keyboard.

      • Example:

        document.addEventListener("keydown", (event) => {
          console.log("Key pressed: " + event.key);
        });
  5. Example of Using addEventListener():

    • You can attach multiple event listeners to the same element without overriding previous listeners.

    • Example:

      let paragraph = document.getElementById("text");
      paragraph.addEventListener("click", () => {
        paragraph.style.color = "blue";  // Change text color on click
      });
      
      paragraph.addEventListener("mouseover", () => {
        paragraph.style.fontSize = "20px";  // Change font size on mouseover
      });

Student Activity (15 mins):

Objective: Students will explore how to use addEventListener() to respond to common DOM events like click, mouseover, and keydown.


Step-by-Step Activity:

  1. Create an HTML file (e.g., dom_events.html) and write JavaScript code to demonstrate the use of addEventListener() for different DOM events.

  2. Example Code:

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Event Listeners and DOM Events</title>
    </head>
    <body>
      <h1 id="heading">Hover over me or click the button!</h1>
      <button id="myButton">Click Me</button>
      <p id="text">This text will change color and size when interacted with.</p>
      <p id="Result">Press any key to see the result here.</p>
    
      <script>
        // Change text color on button click
        let button = document.getElementById("myButton");
        button.addEventListener("click", function() {
          let heading = document.getElementById("heading");
          heading.innerText = "Button Clicked!";
          heading.style.color = "green";  // Change heading color
        });
    
        // Change paragraph style on hover
        let paragraph = document.getElementById("text");
        paragraph.addEventListener("mouseover", function() {
          paragraph.style.color = "blue";  // Change text color
          paragraph.style.fontSize = "22px";  // Change font size
        });
    
        // Reset paragraph style when mouse leaves
        paragraph.addEventListener("mouseout", function() {
          paragraph.style.color = "black";  // Reset text color
          paragraph.style.fontSize = "16px";  // Reset font size
        });
    
        // Log key presses
        document.addEventListener("keydown", function(event) {
          console.log("Key pressed: " + event.key);  // Logs the key pressed
          document.getElementById("Result").textContent =
              "Key pressed: " + event.key
        });
      </script>
    </body>
    </html>
  3. Run the file in a browser:

    • Open the HTML file in a browser and interact with the elements:

      • Click the button to change the heading text and color.

      • Hover over the paragraph to change its text color and font size.

      • Observe how key presses are logged in the console.


Explanation of the Code:

  • Click Event: The button changes the heading text and color when clicked using the click event listener.

  • Mouseover and Mouseout Events: The paragraph’s text changes color and size when hovered over, and resets to the original style when the mouse moves away.

  • Keydown Event: The key pressed by the user is logged to the console, allowing interaction with keyboard input.


Challenge:

  1. Add Multiple Events to the Same Element:

    • Attach multiple event listeners to the button: one for a single click and another for a double-click (dblclick).

    Example:

    button.addEventListener("dblclick", function() {
      heading.innerText = "Button Double-Clicked!";
      heading.style.color = "red";
    });
  2. Extra Challenge:

    • Create a new input field where the text changes dynamically based on user input (use the input event).

    Example:

    <input type="text" id="userInput" placeholder="Type something...">
    <p id="displayText"></p>
    
    <script>
      let inputField = document.getElementById("userInput");
      let displayText = document.getElementById("displayText");
    
      inputField.addEventListener("input", function() {
        displayText.innerText = inputField.value;  // Display the typed text
      });
    </script>

Activity Follow-up Questions:

  1. What is the benefit of using addEventListener() to attach events to elements?

  2. How does the mouseover event differ from the click event in terms of user interaction?

  3. Can you think of real-world use cases where keydown or input events could be useful?


Expected Outcome:

Students will:

  • Understand how to use addEventListener() to respond to common DOM events such as click, mouseover, and keydown.

  • Practice adding multiple event listeners to a single element and handle different types of user interactions.

  • Explore how event listeners make web pages interactive, enhancing user experience and engagement.

Last updated