learn2kode.in

JavaScript Events & Event Listeners

JavaScript events allow your web pages to respond to user actions such as clicks, typing, mouse movement, form submission, and more. Event listeners are used to detect these events and execute code when they occur.
This concept is core for DOM manipulation and React fundamentals, so mastering it is essential.

What Is a JavaScript Event?

An event is an action that happens in the browser, triggered by the user or the system.
Common Examples
What Is an Event Listener?
An event listener is a function that waits for a specific event to happen on a specific element and then runs code in response.
Basic Event Example
<button id="btn">Click Me</button>

<script>
  document.getElementById("btn").addEventListener("click", function () {
    alert("Button clicked!");
  });
</script>
When the button is clicked, the event listener executes the function.
addEventListener() Syntax
element.addEventListener(event, function, useCapture);
Parameters:
Common JavaScript Events
Mouse Events
Keyboard Events
Form Events
Window Events
Example: Click Event
const button = document.querySelector("#btn");

button.addEventListener("click", () => {
  console.log("Button was clicked");
});
Example: Input Event
<input type="text" id="name" />

<script>
  document.getElementById("name").addEventListener("input", function () {
    console.log(this.value);
  });
</script>

Runs every time the user types.

Using the Event Object
JavaScript automatically passes an event object.
document.addEventListener("click", function (event) {
  console.log(event.target);
});
Useful properties:
Prevent Default Behavior
document.querySelector("form").addEventListener("submit", function (e) {
  e.preventDefault();
  alert("Form submission stopped!");
});
Commonly used in form validation and React apps.
Inline Events (Not Recommended)
<button onclick="sayHello()">Click</button>

<script>
  function sayHello() {
    alert("Hello");
  }
</script>
Avoid inline events in modern JavaScript.
Event Bubbling vs Capturing (Basics)
element.addEventListener("click", handler, true); // capturing
Comparison Table: Inline Events vs Event Listeners
Feature Inline Events Event Listeners
Code separation No Yes
Multiple handlers No Yes
Modern practice ❌ Not recommended ✅ Recommended
React compatibility Poor Excellent
Why Events Are Important for React?
Best Practices