JavaScript Fundamentals / Events

Event Listeners

👂Event Listeners

An event listener is a procedure in JavaScript that waits for an event to occur — like a user clicking a button, hovering, typing, or scrolling.

It allows your web page to respond to user interactions dynamically.


🧠 Why Use Event Listeners?

  • To make websites interactive and responsive

  • To execute code only when a specific event happens

  • To separate JavaScript logic from HTML markup

element.addEventListener(event, callbackFunction);

🔹 Parameters:

  • event: Type of event to listen for (e.g., "click", "keydown", "mouseover")

  • callbackFunction: Function to execute when the event occurs


🔍 Example: Click Event

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Button Click Example</title>
</head>
<body>

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

  <script>
    const button = document.getElementById('btn');
    button.addEventListener('click', function () {
      alert('Button clicked!');
    });
  </script>

</body>
</html>

📝 When the user clicks the button, an alert box appears.


🔁 Commonly Used Events

Event Name

Triggered When...

click

Element is clicked

dblclick

Double click

mouseover

Mouse moves over element

mouseout

Mouse leaves the element

keydown

Key is pressed down

keyup

Key is released

submit

Form is submitted

change

Form element changes

scroll

Page or element is scrolled