// Select an element const element = document.getElementById("my-element"); // Attach an event listener to the element element.addEventListener("click", () => console.log("Clicked!"));
In this code, the
addEventListener method is used to attach a click event listener to the
my-element element. This listener will be executed whenever the user clicks on the element. In this case, it simply logs the string “Clicked!” to the console.
Event listeners can be attached to any DOM element, and you can use them to listen for a wide range of different events, including user input events (such as clicks, key presses, and mouse movements), page events (such as loading, scrolling, and resizing), and other types of events. You can also remove an event listener.
To listen for a mouseover event on an element, you can use the
mouseover event type:
// Select an element const element = document.getElementById("my-element"); // Attach a mouseover event listener to the element element.addEventListener("mouseover", () => console.log("Mouseover!"));
To listen for a keypress event on the document, you can use the
keypress event type:
// Attach a keypress event listener to the document document.addEventListener("keypress", (event) => console.log(event.key));
To listen for a page load event, you can use the
load event type:
// Attach a load event listener to the window window.addEventListener("load", () => console.log("Page loaded!"));
Event listeners are an essential part of modern web development, as they allow you to create interactive and dynamic web pages that respond to user input and other events.
I hope this helps! Let me know if you have any questions.