learn2kode.in

JavaScript Events – Complete Beginner Tutorial

What Are JavaScript Events?

JavaScript events are actions or occurrences that happen in the browser and can be detected using JavaScript. These events allow you to make web pages interactive by responding to user actions such as clicks, typing, scrolling, or form submissions.
In simple words, events help JavaScript “listen” and react to user behavior. Common examples of events include:
Understanding JavaScript events is essential before learning React, Vue, or any modern frontend framework.

Why JavaScript Events Are Important

JavaScript events are the foundation of interactive web applications. They allow you to:
Almost every modern website depends on event-driven programming.

Common JavaScript Event Types

Mouse Events
Mouse events are triggered when users interact with the mouse.
Examples:
button.addEventListener("click", function () {
  alert("Button clicked!");
});
Keyboard Events
Keyboard events fire when users press keys.
Examples:
document.addEventListener("keydown", function (event) {
  console.log(event.key);
});
Form Events
Form events are used when handling inputs and forms.
Examples:
form.addEventListener("submit", function (e) {
  e.preventDefault();
  console.log("Form submitted");
});
Window & Page Events
These events occur on the browser window or document.
Examples:
window.addEventListener("scroll", function () {
  console.log("Page scrolling");
});

How JavaScript Events Work

JavaScript follows an event-driven model:

This makes websites responsive and interactive.

Event Handlers in JavaScript

An event handler is a function that runs when an event occurs.
Inline Event Handler (Not Recommended)
<button onclick="alert('Clicked')">Click</button>
❌ Avoid inline handlers because they mix HTML and JavaScript.
Using addEventListener (Recommended)
button.addEventListener("click", function () {
  alert("Clicked using addEventListener");
});
✅ This method is clean, flexible, and used in modern JavaScript and React.

Event Object

When an event happens, JavaScript automatically creates an event object.
button.addEventListener("click", function (event) {
  console.log(event.target);
});
The event object provides useful information like:

Event Bubbling and Capturing (Basic Idea)

JavaScript events move through the DOM in two phases:
element.addEventListener("click", handler, true); // capturing
You don’t need deep knowledge now, but React uses this concept internally.

JavaScript Events and React

If you plan to learn React, JavaScript events are extremely important because:
Learning JavaScript events makes React much easier.

Best Practices for JavaScript Events

Real-World Use Cases