start learning
Image 1
4473323313347

event listener

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.

Here's a step-by-step examples to illustrate the role of event listener :

Creating HTML Structure


<!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


// Access the button element by its ID
const myButton = document.getElementById('myButton');

Adding Event Listener


// 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


// 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


<!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.

×