Event Handling in JavaScript

JavaScript becomes truly powerful when it reacts to user actions.
Click a button. Press a key. Submit a form. Move the mouse. Scroll the page.

These actions are called events, and the process of responding to them is called event handling.

Think of a webpage like a living marketplace:

  • HTML = structure of shops
  • CSS = decoration and beauty
  • JavaScript = people reacting, talking, opening doors, taking orders

Without events, webpages are silent statues.


1. What is an Event?

An event is an action that happens in the browser.

Examples:

  • User clicks a button
  • User types in an input box
  • Page loads
  • Mouse moves
  • Form submits
  • Key is pressed

JavaScript can detect these actions and execute code.


2. What is Event Handling?

Event handling means:

“When a specific event happens, run some JavaScript code.”

That code is called an:

Event Handler / Event Listener


3. Basic Syntax

element.addEventListener("eventName", functionName)

Example:

let btn = document.getElementById("myBtn");

btn.addEventListener("click", sayHello);

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

4. Understanding the Logic

Step-by-Step Flow

Step 1: User performs an action

User clicks button

Step 2: Browser detects event

Event = click

Step 3: JavaScript listener hears it

addEventListener("click", ...)

Step 4: Function executes

alert("Hello!")

5. Types of Events


A. Mouse Events

Event Description
click Mouse click
dblclick Double click
mouseover Mouse enters
mouseout Mouse leaves
mousedown Mouse button pressed
mouseup Mouse button released
mousemove Mouse moves

Example: Click Event

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

<script>
let btn = document.getElementById("btn");

btn.addEventListener("click", function() {
    alert("Button clicked!");
});
</script>

Example: Mouseover

<div id="box">Hover Here</div>

<script>
let box = document.getElementById("box");

box.addEventListener("mouseover", function() {
    box.style.backgroundColor = "yellow";
});
</script>

B. Keyboard Events

Event Description
keydown Key pressed
keyup Key released
keypress Key typed (old)

Example: Detect Key Press

<input type="text" id="inp">

<script>
let inp = document.getElementById("inp");

inp.addEventListener("keydown", function(event) {
    console.log("Key pressed:", event.key);
});
</script>

Logic

When user presses:

A

Browser creates an event object:

event.key = "a"

JavaScript reads it.


C. Form Events

Event Description
submit Form submitted
change Input changed
input User typing
focus Input selected
blur Input loses focus

Example: Form Submit

<form id="myForm">
    <input type="text">
    <button type="submit">Submit</button>
</form>

<script>
let form = document.getElementById("myForm");

form.addEventListener("submit", function(event) {
    event.preventDefault();

    alert("Form submitted!");
});
</script>

Important: preventDefault()

Normally form reloads the page.

event.preventDefault();

Stops default browser behavior.


D. Window Events

Event Description
load Page fully loaded
resize Window resized
scroll Page scrolled

Example: Scroll Event

window.addEventListener("scroll", function() {
    console.log("Scrolling...");
});

6. Ways to Handle Events

There are 3 methods.


Method 1: Inline Event Handling (Old)

<button onclick="sayHello()">Click</button>
function sayHello() {
    alert("Hello");
}

Problem

  • Mixes HTML + JS
  • Hard to manage

Not recommended for large projects.


Method 2: DOM Property

btn.onclick = function() {
    alert("Clicked");
}

Problem

Only one event can exist.


Method 3: addEventListener() ✅ Best Method

btn.addEventListener("click", function() {
    alert("Clicked");
});

Advantages:

  • Multiple listeners allowed
  • Cleaner code
  • Professional approach

7. Event Object

Whenever an event occurs, browser creates an object containing details.

Example:

btn.addEventListener("click", function(event) {
    console.log(event);
});

Useful Properties

Property Meaning
event.target Element that triggered event
event.type Event name
event.key Pressed key
event.clientX Mouse X position
event.clientY Mouse Y position

Example

document.addEventListener("click", function(event) {
    console.log(event.clientX);
    console.log(event.clientY);
});

8. this Keyword in Events

Inside event handler:

this

refers to the element receiving the event.


Example

btn.addEventListener("click", function() {
    this.style.backgroundColor = "red";
});

9. Event Bubbling

One of the MOST IMPORTANT concepts.


What is Bubbling?

Events move upward in DOM hierarchy.

Example:

<div id="parent">
    <button id="child">Click</button>
</div>

If button clicked:

  1. Button event runs
  2. Parent event runs
  3. Body event runs
  4. Document event runs

This is called:

Event Bubbling


Example

child.addEventListener("click", function() {
    console.log("Child clicked");
});

parent.addEventListener("click", function() {
    console.log("Parent clicked");
});

Output:

Child clicked
Parent clicked

10. stopPropagation()

Stops bubbling.

child.addEventListener("click", function(event) {
    event.stopPropagation();

    console.log("Child only");
});

Now parent won't execute.


11. Event Capturing

Opposite of bubbling.

Flow:

Document → Parent → Child

Use third parameter:

addEventListener("click", handler, true)

12. Event Delegation (Very Important)

Used in professional development.

Instead of adding listeners to many children, add ONE listener to parent.


Example

<ul id="list">
    <li>Apple</li>
    <li>Mango</li>
    <li>Banana</li>
</ul>
let list = document.getElementById("list");

list.addEventListener("click", function(event) {
    console.log(event.target.textContent);
});

Logic

User clicks:

Banana

Event bubbles to ul.

event.target tells which li was clicked.

Efficient and scalable.


13. Removing Event Listeners

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

btn.addEventListener("click", greet);

btn.removeEventListener("click", greet);

14. Real-Life Examples


Example 1: Toggle Dark Mode

<button id="darkBtn">Dark Mode</button>

<script>
let darkBtn = document.getElementById("darkBtn");

darkBtn.addEventListener("click", function() {
    document.body.classList.toggle("dark");
});
</script>

Example 2: Live Character Counter

<textarea id="text"></textarea>
<p id="count">0</p>

<script>
let text = document.getElementById("text");
let count = document.getElementById("count");

text.addEventListener("input", function() {
    count.textContent = text.value.length;
});
</script>

Example 3: Show Password

<input type="password" id="pass">
<button id="show">Show</button>

<script>
let pass = document.getElementById("pass");
let show = document.getElementById("show");

show.addEventListener("click", function() {

    if(pass.type === "password") {
        pass.type = "text";
    } else {
        pass.type = "password";
    }

});
</script>

15. Common Beginner Mistakes


Mistake 1

btn.addEventListener("click", greet());

❌ Wrong

This executes immediately.


Correct

btn.addEventListener("click", greet);

Mistake 2

Using element before DOM loads.


Mistake 3

Confusing event.target and this

Keyword Meaning
this Current element
event.target Actual clicked element

16. DOM Event Flow

The full flow:

Capturing Phase
↓
Target Phase
↓
Bubbling Phase

17. Best Practices

✅ Use addEventListener()
✅ Use event delegation for many elements
✅ Keep handlers small
✅ Separate HTML/CSS/JS
✅ Prevent unnecessary DOM updates
✅ Remove unused listeners


18. Mini Project Example

Color Changer

<button id="red">Red</button>
<button id="blue">Blue</button>

<script>
document.getElementById("red")
.addEventListener("click", function() {
    document.body.style.backgroundColor = "red";
});

document.getElementById("blue")
.addEventListener("click", function() {
    document.body.style.backgroundColor = "blue";
});
</script>

19. Interview Questions


Q1: Difference between onclick and addEventListener?

onclick addEventListener
One event only Multiple events
Old method Modern method
Less flexible More powerful

Q2: What is event bubbling?

Event moving upward from child to parent.


Q3: What is event delegation?

Using one parent listener to manage multiple child elements.


20. Final Summary

Concept Meaning
Event User/browser action
Event Handler Function responding to event
addEventListener Modern event handling
Event Object Contains event details
Bubbling Child → Parent
Capturing Parent → Child
Delegation Parent handles child events

Golden Line to Remember

“JavaScript events are the bridge between user actions and application behavior.”

Without events:

  • buttons cannot react
  • forms cannot validate
  • apps cannot interact
  • webpages remain lifeless

Events are the heartbeat of modern web applications.

List of Modules