DEV Community

Jaya Sudha
Jaya Sudha

Posted on

JavaScript Events Made Simple: A Beginner-Friendly Guide

Modern websites are interactive. When you click a button, type in a search box, or submit a form, something happens.

This behavior is possible because of JavaScript Events.

In this blog, we will learn:

  1. Introduction to Events
  2. How Events Work
  3. Common Event Types
  4. The Event Object
  5. Event Propagation
  6. Event Delegation
  7. Removing Event Listeners

Let’s start.

1. Introduction to Events

An event is an action that happens in the browser.

Events can be triggered by:

  • User actions
  • Browser actions

Examples of events

Action Event
Clicking a button click
Typing in keyboard keydown
Submitting a form submit
Moving mouse over element mouseover
Page loaded load

Example

<button id="btn">Click Me</button>
Enter fullscreen mode Exit fullscreen mode
document.getElementById("btn").addEventListener("click", function(){
    alert("Button clicked!");
});
Enter fullscreen mode Exit fullscreen mode

Output

When the user clicks the button, an alert message appears.

This is called interactivity.

Without events, websites would be static like a newspaper page.

2. How Events Work

JavaScript uses an event-driven model.

This means the browser waits for events and then runs code.

The process

  1. User performs an action
  2. Browser detects the event
  3. JavaScript runs the event handler

Syntax of addEventListener

element.addEventListener("event", function)
Enter fullscreen mode Exit fullscreen mode

Example

<button id="btn">Click</button>
Enter fullscreen mode Exit fullscreen mode
let btn = document.getElementById("btn");

btn.addEventListener("click", function(){
    console.log("Button was clicked");
});
Enter fullscreen mode Exit fullscreen mode

Output

Button was clicked
Enter fullscreen mode Exit fullscreen mode

This message appears in the console when the button is clicked.

3. Common Event Types

JavaScript has many event types.

1. Mouse Events
Triggered by mouse actions.

Event Description
click user clicks
dblclick double click
mouseover mouse enters element
mouseout mouse leaves element

Example

<div id="box">Hover over me</div>
Enter fullscreen mode Exit fullscreen mode
let box = document.getElementById("box");

box.addEventListener("mouseover", function(){
    box.style.background = "yellow";
});

box.addEventListener("mouseout", function(){
    box.style.background = "white";
});
Enter fullscreen mode Exit fullscreen mode

Output
When the mouse enters the box → yellow background
When the mouse leaves → white background

2. Keyboard Events

Triggered when keys are pressed.

Event Description
keydown key pressed
keyup key released
keypress key pressed (older event)

Example

<input type="text" id="inputBox">
Enter fullscreen mode Exit fullscreen mode
let input = document.getElementById("inputBox");

input.addEventListener("keydown", function(event){
    console.log("Key pressed:", event.key);
});
Enter fullscreen mode Exit fullscreen mode

Output

Typing A B C

Console shows

Key pressed: A
Key pressed: B
Key pressed: C
Enter fullscreen mode Exit fullscreen mode

3. Form Events

Used when working with forms.

Event Description
submit form submitted
change value changed
input typing
focus field selected
blur field left

Example

<form id="form">
<input type="text">
<button>Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode
let form = document.getElementById("form");

form.addEventListener("submit", function(event){
    event.preventDefault();
    alert("Form submitted!");
});
Enter fullscreen mode Exit fullscreen mode

Output
The alert appears without refreshing the page.

4. Window / Document Events

These events happen on the browser window.

Event Description
load page fully loaded
DOMContentLoaded HTML loaded
resize window resized
scroll page scrolled

Example

window.addEventListener("scroll", function(){
    console.log("User is scrolling");
});
Enter fullscreen mode Exit fullscreen mode

4. The Event Object

Whenever an event occurs, JavaScript creates an event object.

This object contains information about the event.

Example

document.addEventListener("click", function(event){
    console.log(event.target);
});
Enter fullscreen mode Exit fullscreen mode

Important Properties

Property Meaning
event.target element clicked
event.type type of event
event.key key pressed
event.clientX mouse X position
event.clientY mouse Y position

Example

document.addEventListener("click", function(event){
    console.log("Clicked element:", event.target);
    console.log("Event type:", event.type);
});
Enter fullscreen mode Exit fullscreen mode

Prevent Default Behaviour

Some elements have default actions.

Example:

  • Form reload
  • Link navigation

We can stop it using:

event.preventDefault()
Enter fullscreen mode Exit fullscreen mode

Example

<a href="https://google.com" id="link">Go to Google</a>
Enter fullscreen mode Exit fullscreen mode
document.getElementById("link").addEventListener("click", function(event){
    event.preventDefault();
    alert("Link prevented!");
});

Enter fullscreen mode Exit fullscreen mode

5. Event Propagation [To Be Discussed]

When an event happens inside nested elements, it travels through the DOM.

This is called event propagation.

There are two phases:

1. Event Bubbling

Event goes from child → parent → document

Example:

<div id="parent">
<button id="child">Click</button>
</div>
Enter fullscreen mode Exit fullscreen mode
document.getElementById("child").addEventListener("click", function(){
    console.log("Child clicked");
});

document.getElementById("parent").addEventListener("click", function(){
    console.log("Parent clicked");
});
Enter fullscreen mode Exit fullscreen mode

Output

Child clicked
Parent clicked

Enter fullscreen mode Exit fullscreen mode

Because event bubbles up.

2. Event Capturing

Event goes from parent → child

addEventListener("click", function, true)
Enter fullscreen mode Exit fullscreen mode

Example

document.getElementById("parent").addEventListener("click", function(){
    console.log("Parent capturing");
}, true);
Enter fullscreen mode Exit fullscreen mode

stopPropagation()

Stops the event from moving further.

document.getElementById("child").addEventListener("click", function(event){
    event.stopPropagation();
    console.log("Child only");
});
Enter fullscreen mode Exit fullscreen mode

Output

Child only
Enter fullscreen mode Exit fullscreen mode

Parent event will not run.

Example

document
   ↓
body
   ↓
parent
   ↓
child (clicked)
   ↑
parent
   ↑
body
   ↑
document
Enter fullscreen mode Exit fullscreen mode
  • Capturing → top to bottom
  • Bubbling → bottom to top

6. Event Delegation

Instead of adding many event listeners, we can add one listener to the parent.

This technique is called event delegation.

It improves performance.

Example 1

<ul id="list">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>
Enter fullscreen mode Exit fullscreen mode
document.getElementById("list").addEventListener("click", function(event){

    if(event.target.tagName === "LI"){
        console.log("You clicked:", event.target.innerText);
    }

});
Enter fullscreen mode Exit fullscreen mode

Output

Clicking any item shows:(The exact element that was clicked by the user)

You clicked: Item 2
Enter fullscreen mode Exit fullscreen mode

Even if new <li> is added later, it still works.

7. Removing Event Listeners

We can remove an event listener using:

removeEventListener()

But the function must be named.

Example

function sayHello(){
    console.log("Hello");
}

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

btn.addEventListener("click", sayHello);

btn.removeEventListener("click", sayHello);
Enter fullscreen mode Exit fullscreen mode

Anonymous functions cannot be removed easily.

Conclusion
JavaScript events are essential for creating interactive web applications. Understanding how events work helps developers handle user actions effectively and build dynamic user interfaces.

Top comments (0)