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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay