Yandex

JavaScript Event Handling
click, submit, keydown, bubbling, delegation & more



Event Handling in JavaScript

Events are the heartbeat of any interactive web application. Whether you're clicking a button, pressing a key, or submitting a form, events allow JavaScript to respond to user actions. This tutorial takes you from foundational event handling to advanced topics like event bubbling and delegation.

What is an Event?

An event is an action or occurrence that happens in the browser — like a user click, mouse movement, or a keystroke. JavaScript lets you listen to these events and react accordingly.

Basic Event Handling Using HTML Attributes

The simplest way to handle events is by adding event attributes directly in HTML.


<button onclick="alert('Button clicked!')">Click Me</button>

Event Handling with JavaScript (Recommended)

Using JavaScript to attach events is more flexible and maintainable.


const btn = document.querySelector("button");

btn.addEventListener("click", function () {
  alert("Button was clicked!");
});
(Button clicked, an alert appears)

Types of Common Events

  • click – when a user clicks an element
  • submit – when a form is submitted
  • keydown, keyup – when a key is pressed or released
  • mouseover, mouseout – when mouse hovers or leaves an element
  • change – when input value changes

Example: Handling a Form Submit Event


<form id="loginForm">
  <input type="text" id="username" placeholder="Username" required />
  <button type="submit">Login</button>
</form>

document.getElementById("loginForm").addEventListener("submit", function(e) {
  e.preventDefault();
  const user = document.getElementById("username").value;
  alert("Logged in as " + user);
});
Typed "john", clicked login => Alert: Logged in as john

Keyboard Events: keydown vs keyup


<input type="text" id="searchBox" placeholder="Type something..." />
<p id="log"></p>

const input = document.getElementById("searchBox");
const log = document.getElementById("log");

input.addEventListener("keydown", function(e) {
  log.textContent = "Key down: " + e.key;
});
Pressing "A" → Key down: a

Mouse Events Example


<div id="hoverBox" style="width:200px;height:100px;background:#ddd">
  Hover me!
</div>
<p id="status"></p>

const box = document.getElementById("hoverBox");
const status = document.getElementById("status");

box.addEventListener("mouseover", () => {
  status.textContent = "Mouse entered the box.";
});

box.addEventListener("mouseout", () => {
  status.textContent = "Mouse left the box.";
});
Mouse entered → "Mouse entered the box."
Mouse exited → "Mouse left the box."

Event Object and Its Properties

The event handler receives an event object which holds information like the target, key pressed, mouse position, etc.


document.addEventListener("click", function(e) {
  console.log("Clicked element:", e.target.tagName);
});
Clicked element: BUTTON

Event Bubbling vs Capturing

When you click a nested element, events bubble up from the target to the root. You can also capture events on the way down.


<div id="outer" style="padding:30px; background:lightblue;">
  Outer
  <div id="inner" style="padding:30px; background:lightgreen;">
    Inner
  </div>
</div>

document.getElementById("outer").addEventListener("click", () => {
  console.log("Outer div clicked");
});

document.getElementById("inner").addEventListener("click", () => {
  console.log("Inner div clicked");
});
Click inner → Logs: "Inner div clicked", then "Outer div clicked"

Event Delegation

Instead of adding event listeners to each child, you can attach one to the parent and use event.target to act conditionally.


<ul id="menu">
  <li>Home</li>
  <li>About</li>
  <li>Contact</li>
</ul>

document.getElementById("menu").addEventListener("click", function(e) {
  if (e.target.tagName === "LI") {
    alert("You clicked on " + e.target.textContent);
  }
});
Click "About" → Alert: You clicked on About

Removing Event Listeners


function greet() {
  alert("Hello!");
}

const btn = document.querySelector("button");
btn.addEventListener("click", greet);

// Later in the code
btn.removeEventListener("click", greet);

Custom Events

You can create your own events and dispatch them manually.


const msg = new CustomEvent("greet", {
  detail: { name: "Developer" }
});

document.addEventListener("greet", function(e) {
  console.log("Hello, " + e.detail.name + "!");
});

document.dispatchEvent(msg);
Hello, Developer!


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M