An event listener is a function that waits for a specific event to occur and then executes some code in response to that event. Events can be user interactions like clicks, keypresses, mouse movements, etc., or they can be browser-related events like page load, resizing, etc.
event listener
Here's a step-by-step examples to illustrate the role of event listener :
Creating HTML Structure
- Start by creating the HTML structure where you want to add the event listener. For example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Listener Example</title>
</head>
<body>
<button id="myButton">Click me!</button>
</body>
</html>
Accessing the Element in JavaScript
- To add an event listener to an element, you first need to access that element in JavaScript. You can do this using document.getElementById or other methods.
// Access the button element by its ID
const myButton = document.getElementById('myButton');
Adding Event Listener
- Use the addEventListener method to attach an event listener to the element. The method takes two arguments: the event type and the function to be executed when the event occurs.
// Add a click event listener to the button
myButton.addEventListener('click', function() {
// Code to be executed when the button is clicked
console.log('Button Clicked!');
});
Handling the Event
- Define the function that will be executed when the specified event occurs. This function is commonly referred to as an event handler.
// Event handler function
function buttonClickHandler() {
console.log('Button Clicked!');
// Additional code to be executed
}
// Add the event listener using the function
myButton.addEventListener('click', buttonClickHandler);
Complete Example
- Putting it all together
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Event Listener Example</title>
</head>
<body>
<button id="myButton">Click me!</button>
<script>
/ Access the button element by its ID
const myButton = document.getElementById('myButton');
// Event handler function
function buttonClickHandler() {
console.log('Button Clicked!');
// Additional code to be executed
}
// Add a click event listener to the button
myButton.addEventListener('click', buttonClickHandler);
</script>
</body>
</html>
By following these steps, you can create and understand the use of an event listener in JavaScript.
×