16.5 Event Listeners and DOM Events (15 mins)
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
focusevent occurs when an element gains focus, while theblurevent occurs when an element loses focus
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
falsefor the bubbling phase).
The removeEventListener() Method:
addEventListener()detaches an event handler added to an event handler usingaddEventListener()Syntax:
element.removeEventListener(event, function, useCapture);Explanation:
element: The element on which the event listener is attached.
event: The type of event to listen for (e.g., 'click', 'mouseover', 'keydown').
function: The function that will be executed when the event occurs.
useCapture: An optional boolean value indicating whether the event should be captured. Typically,
falseis used.
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); });
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:
Create an HTML file (e.g.,
dom_events.html) and write JavaScript code to demonstrate the use ofaddEventListener()for different DOM events.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>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
clickevent 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:
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"; });Extra Challenge:
Create a new input field where the text changes dynamically based on user input (use the
inputevent).
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:
What is the benefit of using
addEventListener()to attach events to elements?How does the
mouseoverevent differ from theclickevent in terms of user interaction?Can you think of real-world use cases where
keydownorinputevents could be useful?
Expected Outcome:
Students will:
Understand how to use
addEventListener()to respond to common DOM events such asclick,mouseover, andkeydown.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