Handling Events
One of the key features of JavaScript is its ability to respond to user actions and events. In the context of the DOM, events are actions or occurrences that happen on a web page, such as a button click, mouse movement, or keyboard input. To handle these events, we can use event listeners.
An event listener is a function that listens for a specific event to occur and then executes a block of code in response. It allows us to define custom behavior for various user interactions. For example, we can add an event listener to a button element and specify a function to be executed when the button is clicked.
Here's an example that demonstrates how to add an event listener to a button and log a message when it is clicked:
1// Add an event listener to a button
2const button = document.getElementById('myButton');
3
4button.addEventListener('click', () => {
5 console.log('Button clicked!');
6});
In this example, we first select the button element using its ID. We then call the addEventListener()
method on the button and pass in the event type ('click') and a callback function. The callback function will be executed whenever the button is clicked, and in this case, it logs a message to the console.
Event listeners can be added to any DOM element using various event types, such as 'click', 'mouseover', 'keydown', etc. They provide a powerful way to make web pages interactive and responsive to user actions.
Practice adding event listeners to different elements and handling various events to become comfortable with this important aspect of working with the DOM!
xxxxxxxxxx
// EXAMPLE CODE
// Add an event listener to a button
const button = document.getElementById('myButton');
button.addEventListener('click', () => {
console.log('Button clicked!');
});