In JavaScript, event listeners can be added to HTML elements to execute a block of code when the specified event occurs. Here's an example of how to add a click event listener to a button element:
In the above example, we first select the button element using the querySelector() method and store it in a variable called myButton. Then, we add an event listener to the button using the addEventListener() method, which takes two arguments: the event to listen for (in this case, click), and the function to execute when the event occurs. In this example, we simply log a message to the console when the button is clicked.
We can also add event listeners to other HTML elements, such as input fields, and listen for different events, such as change or submit.
Here's an example of adding an event listener to an input field to listen for changes:
In this example, we select the input element using the querySelector() method and store it in a variable called myInput. We then add an event listener to the input element using the addEventListener() method, and listen for the change event. When the event occurs, the function we specified is executed, which logs a message to the console along with the current value of the input field.
To remove an event listener from an HTML element, we can use the removeEventListener() method. This method requires the same two arguments as addEventListener(): the event to remove, and the function to remove.
Here's an example:
In this example, we define a function called handleClick() that logs a message to the console. We then add an event listener to the button using the addEventListener() method, and pass in the handleClick function. After 5 seconds, we use the removeEventListener() method to remove the event listener from the button, passing in the same arguments that were used to add the listener.
Overall, event listeners are a powerful tool in JavaScript for adding interactivity to web pages and responding to user actions.
Thank you for learning ❤️