How do event listeners work in the DOM?
Asked on Aug 12, 2024
Answer
Event listeners in the DOM allow you to execute a function when a specific event occurs on an element, such as a click or a keypress. You can add an event listener to an element using the "addEventListener" method.
<!-- BEGIN COPY / PASTE -->
const button = document.querySelector('button');
button.addEventListener('click', function() {
alert('Button was clicked!');
});
<!-- END COPY / PASTE -->
Additional Comment:
✅ Answered with JavaScript best practices.- This example selects a button element and attaches a "click" event listener to it.
- When the button is clicked, the function inside "addEventListener" is executed, displaying an alert.
- "addEventListener" can be used for various events like "mouseover", "keydown", etc.
- It is a good practice to use "addEventListener" instead of inline event attributes for better separation of HTML and JavaScript.
Recommended Links:
← Back to All Questions