DEV Community

swetha palani
swetha palani

Posted on

addEventListner() Method in Java script

What is addEventListener()?

The addEventListener() method is used to attach an event (like click, mouseover, keypress, etc.) to an HTML element. It allows you to run a function whenever that event happens.

  • Syntax:
element.addEventListener(event, function, useCapture);

Enter fullscreen mode Exit fullscreen mode
  • element → The HTML element (like button, div, input, etc.)

  • event → Type of event (e.g., "click", "mouseover", "keydown")

  • function → The function to run when the event happens

  • useCapture (optional) → true or false (default is false). Defines event bubbling or capturing.

CLICK EVENT:

<button id="myBtn">Click Me</button>

<script>
  document.getElementById("myBtn").addEventListener("click", function() {
    alert("Button was clicked!");
  });
</script>

Enter fullscreen mode Exit fullscreen mode

When you click the button, an alert will pop up.

  • Multiple Events
let box = document.getElementById("box");

box.addEventListener("mouseover", function() {
  box.style.backgroundColor = "lightblue";
});

box.addEventListener("mouseout", function() {
  box.style.backgroundColor = "lightgreen";
});

Enter fullscreen mode Exit fullscreen mode

Top comments (0)