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);
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>
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";
});
Top comments (0)