CS Engineering Gyan

JavaScript Events

JavaScript events are actions or occurrences that happen in a webpage and can be detected by JavaScript. Events allow websites to respond to user interactions such as clicking a button, typing text, submitting a form, moving the mouse, or loading a webpage.

Events are one of the most important concepts in JavaScript because they make webpages interactive and dynamic. Without events, websites would only display fixed information and users could not interact with webpage elements.

Modern web applications such as online shopping websites, social media platforms, banking systems, and web games heavily depend on JavaScript events.


What are JavaScript Events?

An event is a signal generated by the browser when something happens on a webpage. JavaScript can detect these signals and execute specific code in response.

For example, when a user clicks a login button, a click event occurs. JavaScript can handle this event and verify the user's information.

Simple Example







Output


Button Clicked


Why are JavaScript Events Important?

Events allow developers to create interactive experiences where webpages respond according to user actions.

Advantages of Events


How JavaScript Handles Events

JavaScript handles events using event handlers. An event handler is a block of code that runs when a specific event occurs.

The browser continuously monitors user actions. When an event happens, JavaScript executes the related event handler.


Types of JavaScript Events

JavaScript provides many types of events. The most commonly used events are:

Event Type Description
Mouse Events Triggered by mouse actions.
Keyboard Events Triggered by keyboard actions.
Form Events Related to form operations.
Window Events Related to browser window actions.
Clipboard Events Related to copy and paste operations.

Event Handler Methods

There are different ways to handle events in JavaScript.

1. Inline Event Handling

In this method, event code is written directly inside the HTML element.

Example





2. Using Event Properties

Events can be assigned using JavaScript properties.

Example


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


button.onclick = function()
{

alert("Button Clicked");

}


3. Using addEventListener()

The modern and recommended method for handling events is the addEventListener() method.

Syntax


element.addEventListener(event, function);

Example


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


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

alert("Clicked");

});


Mouse Events in JavaScript

Mouse events occur when a user performs actions using a mouse or touch device.

Common Mouse Events

Event Description
click Occurs when an element is clicked.
dblclick Occurs when an element is double clicked.
mouseover Occurs when mouse moves over an element.
mouseout Occurs when mouse leaves an element.
mousedown Occurs when mouse button is pressed.
mouseup Occurs when mouse button is released.

Click Event

The click event occurs when a user clicks on an HTML element.

Example







Output


Button clicked


Double Click Event

The dblclick event occurs when an element is clicked twice quickly.

Example








Mouse Over Event

The mouseover event occurs when the mouse pointer enters an element.

Example


Move mouse here


Mouse Out Event

The mouseout event occurs when the mouse pointer leaves an element.

Example


Move mouse away


Keyboard Events in JavaScript

Keyboard events occur when a user interacts with a webpage using the keyboard. These events are commonly used for handling user input, search boxes, shortcuts, games, and form validation.

JavaScript provides different keyboard events to detect when keys are pressed or released.


Common Keyboard Events

Event Description
keydown Occurs when a keyboard key is pressed.
keyup Occurs when a keyboard key is released.
keypress Occurs when a character key is pressed.

keydown Event

The keydown event is triggered when a user presses any key on the keyboard.

Example


document.addEventListener("keydown",function()
{

console.log("Key Pressed");

});


Output


Key Pressed


keyup Event

The keyup event occurs when the user releases a pressed key.

Example


document.addEventListener("keyup",function()
{

console.log("Key Released");

});


Output


Key Released


Detecting Specific Keys

JavaScript allows developers to identify which key was pressed using the event object.

Example


document.addEventListener("keydown",function(event)
{

console.log(event.key);

});


If the user presses the A key, the output will be:


A


Keyboard Event Example: Input Counter







Whenever the user types something, the updated value is displayed.


Form Events in JavaScript

Form events are generated when users interact with HTML forms. They are mainly used for form validation, data processing, and improving user experience.


Common Form Events

Event Description
submit Occurs when a form is submitted.
change Occurs when the value of an element changes.
input Occurs when user enters data.
focus Occurs when an element gets focus.
blur Occurs when an element loses focus.

Submit Event

The submit event occurs when a user submits a form.

It is commonly used to validate form data before sending it to a server.

Example



preventDefault() Method

The preventDefault() method prevents the default action of an event.

For example, when a form is submitted, the browser normally reloads the page. This method stops that behavior.

Example


event.preventDefault();


Change Event

The change event occurs when the value of an input element is changed and the user moves away from that element.

Example








Input Event

The input event occurs immediately whenever the user enters or modifies data inside an input field.

Example








Focus Event

The focus event occurs when an element becomes active.

It is commonly used to highlight input fields.

Example








Blur Event

The blur event occurs when an element loses focus.

It is often used for validation after the user completes entering data.

Example








Window Events in JavaScript

Window events are related to browser window activities such as loading a page, resizing the browser, and scrolling.


Common Window Events

Event Description
load Runs when webpage completely loads.
resize Occurs when browser size changes.
scroll Occurs when page scrolling happens.
unload Occurs when page is closed.

load Event

The load event executes when all webpage resources such as images, CSS, and scripts are completely loaded.

Example


window.addEventListener("load",function()
{

alert("Page Loaded");

});


resize Event

The resize event occurs when the browser window size changes.

Example


window.addEventListener("resize",function()
{

console.log("Window Resized");

});


scroll Event

The scroll event occurs when the user scrolls the webpage.

Example


window.addEventListener("scroll",function()
{

console.log("Scrolling");

});


Event Object in JavaScript

The event object contains information about an event that has occurred.

It is automatically passed to the event handler function.

Example


button.addEventListener("click",
function(event)
{

console.log(event);

});


Important Event Object Properties

Property Description
event.type Returns event name.
event.target Returns the element that triggered event.
event.key Returns pressed keyboard key.
event.clientX Returns mouse X position.
event.clientY Returns mouse Y position.

Example Using Event Object


document.addEventListener("click",
function(event)
{

console.log(event.type);

});

Output


click



Event Bubbling in JavaScript

Event bubbling is a process where an event starts from the target element and then moves upward through its parent elements.

In simple words, when an event occurs on a child element, the same event can also be detected by its parent elements.

Example of Event Bubbling


<div id="parent">

    Parent Element

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

</div>


<script>


document.getElementById("child")
.addEventListener("click",function()
{

alert("Button Clicked");

});


document.getElementById("parent")
.addEventListener("click",function()
{

alert("Parent Clicked");

});


</script>

Output


Button Clicked

Parent Clicked

When the button is clicked, first the button event executes and then the parent event executes.


Event Capturing in JavaScript

Event capturing is the opposite process of event bubbling. In capturing, the event starts from the top-level parent element and moves toward the target element.

Event capturing is also called the trickling phase.

Syntax


element.addEventListener(
event,
function,
true
);

The third parameter true enables event capturing.


Difference Between Event Bubbling and Capturing

Event Bubbling Event Capturing
Event moves from child to parent. Event moves from parent to child.
Default behavior in JavaScript. Needs to be enabled manually.
Called bubbling phase. Called capturing phase.
Commonly used in applications. Used for special event handling.

Stopping Event Propagation

Sometimes developers do not want an event to move from one element to another. JavaScript provides the stopPropagation() method for this purpose.

Example


button.addEventListener("click",
function(event)
{

event.stopPropagation();


alert("Button Event");

});

After using stopPropagation(), the event will not move to parent elements.


Event Delegation in JavaScript

Event delegation is a technique where a single event handler is added to a parent element instead of adding separate handlers to multiple child elements.

It works because of event bubbling.

Advantages of Event Delegation


Example of Event Delegation


<ul id="menu">

<li>Home</li>

<li>About</li>

<li>Contact</li>

</ul>


<script>


document.getElementById("menu")
.addEventListener("click",function(event)
{

alert(event.target.innerHTML);

});


</script>

Output


Home

About

Contact


Mouse Event Properties

Mouse events provide additional information through the event object.

Common Mouse Properties

Property Description
clientX Mouse position from left side of browser.
clientY Mouse position from top side of browser.
button Returns mouse button information.
target Returns clicked element.

Example: Detect Mouse Position


document.addEventListener("mousemove",
function(event)
{

console.log(
event.clientX,
event.clientY
);

});

The browser displays the current mouse coordinates.


Creating Custom Events

JavaScript allows developers to create their own custom events according to application requirements.

Custom events are useful when different parts of an application need to communicate with each other.

Creating Custom Event


let myEvent = new Event("message");


document.dispatchEvent(myEvent);


Listening to Custom Events


document.addEventListener(
"message",
function()
{

console.log("Custom Event Executed");

});


Output


Custom Event Executed


Practical Event-Based Programs


Program 1: Change Text on Button Click





Hello User

Output


Welcome JavaScript


Program 2: Show Password










This type of event is commonly used in login forms.


Program 3: Button Color Change








Real-World Applications of JavaScript Events

Events are the foundation of interactive web applications. Almost every modern website uses events.


Common Mistakes While Using Events


Best Practices for JavaScript Events


JavaScript Events Interview Questions

  1. What are JavaScript events?
  2. Why are events important in JavaScript?
  3. What is event handling?
  4. Explain addEventListener().
  5. Difference between onclick and addEventListener().
  6. What are mouse events?
  7. Explain keyboard events.
  8. What is event bubbling?
  9. What is event capturing?
  10. Explain event delegation.
  11. What is stopPropagation()?
  12. What is preventDefault()?
  13. What is an event object?
  14. How can you create custom events?
  15. Difference between input and change events.

Summary

JavaScript events allow webpages to respond to user actions and browser activities. Events make websites interactive, dynamic, and user-friendly.

Important event concepts include mouse events, keyboard events, form events, window events, event objects, bubbling, capturing, delegation, and custom events.

A strong understanding of JavaScript events helps developers create modern web applications with better user interaction and improved functionality.


← Previous: JavaScript Strings Next: DOM Manipulation →
Home Visit Our YouTube Channel