DEV Community

Saman Mahmood
Saman Mahmood

Posted on

ADD EVENT LISTENER IN JavaScript

Here's an example of how to add an event listener in JavaScript:

Suppose you have an HTML button with the ID "myButton," and you want to add a click event listener to it. When the button is clicked, an alert will display a message.

HTML:

<button id="myButton">Click Me</button>
Enter fullscreen mode Exit fullscreen mode

JavaScript:

// _Get a reference to the button element by its ID_
const myButton = document.getElementById("myButton");

// _Add a click event listener to the button_
myButton.addEventListener("click", function() {
  // _Code to be executed when the button is clicked_
  alert("Button clicked!");
});
Enter fullscreen mode Exit fullscreen mode

In this example, when you click the "Click Me" button, the event listener function will be executed, and it will display an alert with the message "Button clicked!".

You can similarly add event listeners to other HTML elements and for various events like "mouseover," "keydown," "change," etc. Just replace "click" with the appropriate event type you want to listen for.

Top comments (0)