View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Javascript Events

Updated on 03/02/2025459 Views

JavaScript events are a crucial part of making our websites or web applications more dynamic. According to me, and realistically speaking, websites would essentially become digital brochures without events.

Any change, even minor ones, would require the entire page to refresh from the server. This leads to a slow and clunky user experience. Drag and drop interfaces, smooth transitions, etc. would all be impossible without using events in JS.

I strongly believe that the JavaScript events library is an essential part of web development when your tool of choice is JS. It helps to be well-versed with events when working with JS-based stacks such as MERN or MEAN.

I will cover JavaScript events with examples in detail and also share a JavaScript event list with you in this tutorial.

What Are JavaScript Events?

Events are signals triggered by the browser that communicate something has happened on our webpage. This could be user interactions (like mouse clicks, typing, etc.), browser actions (like page getting loaded), or other occurrences.

Events allow our JavaScript code to "listen" for these signals and dynamically respond. This is the foundation of making websites interactive. For example, without JavaScript events, real-time updates (like in stock tickers or chat applications), auto-complete suggestions, or dropdown menus that appear as you type would just not work.

Not using JavaScript events can also create a potential security vulnerability as unvalidated data reaches the server. There are plenty of other issues such as delayed error feedback to the user, no validation message pop-ups, and more.

Types of JavaScript Events

Let us learn about the essential JavaScript event types with the help of this JavaScript events list with examples of some of the events.

1. Mouse Events

  • click: A mouse button is clicked.
  • mouseover: The mouse hovers over an element.
  • mouseout: The mouse leaves an element.
  • mousedown: A mouse button is pressed down.
  • mouseup: A mouse button is released.

2. Keyboard Events

  • keydown: A key is pressed.
  • keyup: A key is released.

3. Form Events

  • submit: A form is submitted.
  • change: The content of a form element changes.
  • focus: An element gets focus (e.g., a text input is clicked on).
  • blur: An element loses focus.

4. Window Events

  • load: The page is finished loading.
  • resize: The browser window is resized.

Handling JavaScript Events

There are two primary ways to handle events in JavaScript. Let us learn about them both in this JavaScript event tutorial.

Inline Event Handlers (Less Ideal)

We can directly embed JavaScript within HTML attributes. The downside of this method is that it mixes your JavaScript with HTML structure, potentially making your code harder to maintain.

Example:

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

Event Listeners (Recommended)

We can use addEventListener to attach event handlers to elements. Event listeners allow clean separation of concerns and the attaching of multiple handlers to the same event.

However, excessive event listeners can impact website performance, especially with event delegation. Thus, even though I would personally recommend this method for JavaScript events methods, we should use it wisely.

Example:

const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Hello!');
});

Note: Within an event handler function, the this keyword usually refers to the element the event was triggered on.

Examples of JavaScript Events in Pages

Let us now explore some working examples of JavaScript events.

Creating a Button Alert

<!DOCTYPE html>
<html>
<head>
<title>Event Example</title>
</head>
<body>
<button id="myButton">Click Me</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
alert('Button clicked!');
});
</script>
</body>
</html>

In the above code, <button id="myButton">Click Me</button> creates a button with the text "Click Me" on it. The id gives the button a unique name. The const button = document.getElementById('myButton'); line finds the button you created using its id and stores a reference to it in the button variable.

The button.addEventListener('click', function() { ... }); tells the button to "listen" for a click event. When the click happens, the code inside the function() will execute. Finally, alert('Button clicked!'); is the action that occurs when the button is clicked. It causes a pop-up alert to appear saying "Button clicked!".

Button Changes Its Own Color

<!DOCTYPE html>
<html>
<head>
<title>Event Example</title>
</head>
<body>
<button id="myButton">Click Me</button>
<script>
const button = document.getElementById('myButton');
button.addEventListener('click', function() {
this.style.backgroundColor = 'blue'; // 'this' refers to the button
});
</script>
</body>
</html>

In this code, we select the button element using its ID (myButton). We then add a 'click' event listener to the button. When the button is clicked by the user, the anonymous function we provided is executed as the event handler.

Inside the function, the keyword this refers to the element that triggered the event – the button itself. We use this.style.backgroundColor = 'blue' to change the button's background color directly.

Note: Events can 'bubble up' or 'capture down' the HTML element tree. This is relevant if you have multiple nested elements handling the same event type. Also, when using JavaScript events, we should always check for compatibility (older browsers might have quirks).

Advanced JavaScript Events Program

Let us develop a more advanced JavaScript events example with heavier design elements.

I will be using two images hosted on our website to show you this example, however, you can modify the code and use any image of your choice. We will be making 3 files for this, index.html, styles.css, and script.js.

After compilation:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Gallery</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="gallery-container">
<h1>Image Gallery</h1>
<div class="image-grid">
<img src="https://www.upgrad.com/_ww3-next/_next/static/media/upGrad-logo.6366986e.svg" alt="Image 1" class="gallery-image">
<img src="https://www.upgrad.com/_ww3-next/_next/static/media/upgrad-header-logo.19ba8cde.svg" alt="Image 2" class="gallery-image">
</div>
<div class="modal" id="imageModal">
<span class="close-btn" id="closeModal">&times;</span>
<img class="modal-image" id="modalImage">
</div>
</div>
<script src="script.js"></script>
</body>
</html>

Here is the code for styles.css:

/* Basic Styling */
body { font-family: Arial, sans-serif; margin: 0; padding: 20px;}
.gallery-container { text-align: center;}
.image-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px;}
.gallery-image { width: 100%; cursor: pointer; transition: transform 0.3s ease;}
.gallery-image:hover { transform: scale(1.05); }
/* Modal Styling */
.modal { display: none; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: rgba(0,0,0,0.8); padding: 20px; z-index: 1000; /* Ensure modal is on top */}
.modal-image { max-width: 80%; max-height: 80%; }
.close-btn { position: absolute; top: 10px; right: 10px; color: #fff; font-size: 2em; cursor: pointer;}

Here is the code for script.js:

const galleryImages = document.querySelectorAll('.gallery-image');
const modal = document.getElementById('imageModal');
const modalImage = document.getElementById('modalImage');
const closeBtn = document.getElementById('closeModal');
galleryImages.forEach(img => {
img.addEventListener('click', (event) => {
modal.style.display = 'block';
modalImage.src = event.target.src;
});
});
closeBtn.addEventListener('click', () => {
modal.style.display = 'none';
});
// Optional: Close modal on outside click
window.addEventListener('click', (event) => {
if (event.target === modal) {
modal.style.display = 'none';
}
});

In the above program, const galleryImages = document.querySelectorAll('.gallery-image'); selects all image elements with the class gallery-image into a galleryImages constant. Then, the const modal = document.getElementById('imageModal'); selects the element with the ID imageModal (the modal) and stores it in the modal constant.

Finally, similar lines select the modalImage (image displayed in modal) and closeBtn (close button) elements and store them in constants. The galleryImages.forEach(img => { ... }); loops through each image in the galleryImages constant and executes the code within

Additional JavaScript Events Examples

Here are some more JavaScript events with examples:

Submitting a Form

<form onsubmit="return validateForm()">
<button type="submit">Submit</button>
</form>
<script>
function validateForm() {
// Your form validation logic here
return true; // Allow submission if valid
}
</script>

Page Loading

<!DOCTYPE html>
<html>
<head>
<h1>Event Example</h1>
</head>
<body onload="alert('Page finished loading!')">
</body>
</html>

JavaScript Events Advanced Concepts

Let us now learn about JavaScript events in more detail.

Event Objects

When an event fires, an event object is automatically passed to your event handler function. This object carries rich information about the event:

  • type: The type of event (e.g., 'click', 'mouseover').
  • target: The element that triggered the event.
  • clientX, clientY: Mouse coordinates (for mouse events).
  • key, keyCode: Information about the pressed key (for keyboard events).
  • And many more properties depending on the event type.

Example: Logging event details

Code snippet:

const inputField = document.getElementById('myInput');
inputField.addEventListener('change', function(event) {
console.log('Event type:', event.type);
console.log('Target element:', event.target);
console.log('New value:', event.target.value);
});

stopPropagation() and preventDefault()

stopPropagation() prevents the event from bubbling up to parent elements. This is useful if you want an event to be handled only by a specific element and not its ancestors.

Meanwhile, preventDefault() cancels the default behavior associated with certain events. For example, calling preventDefault() on a form's submit event prevents the form from actually being submitted.

Example: Stopping link behavior

Code snippet:

const link = document.getElementById('myLink');
link.addEventListener('click', function(event) {
event.preventDefault(); // Prevent the link from being followed
// Custom behavior here...
});

Event Delegation

Event delegation is a powerful technique for optimizing event handling, especially when dealing with lots of dynamically created elements. We can attach a single event listener to a parent element and use event properties to determine which child element actually triggered the event.

Example: Handling clicks on dynamic list items

Code snippet:

const list = document.getElementById('myList');
list.addEventListener('click', function(event) {
if (event.target.tagName === 'LI') { // Check if a list item was clicked
// Handle the click on the list item
}
});

JavaScript Events Practice

Now that we have reached this point, I want you to try these out yourself:

  • A scenario where you use event.stopPropagation() to create a self-contained interactive element.
  • Implementing a custom form validation routine using preventDefault().
  • Setting up a drag-and-drop behavior for elements on your page using mouse events.

Wrapping Up

While technically it's possible to build a website without JavaScript events, the result would be drastically limited. Modern web development relies heavily on events for interactivity, efficiency, and an enhanced user experience.

Without JavaScript events, our websites would not respond to user actions in real-time and users would need to go through an unnecessary number of page reloads. Not needing our users to reload the site often also optimizes data transfer to the server.

If you wish to master JavaScript and other essential tools, you can join upGrad’s online tech programs.

Frequently Asked Questions

  1. What are JavaScript events?

JavaScript events are signals that notify your code about user interactions, browser actions, or other occurrences on a webpage.

  1. What are JavaScript form events?

JavaScript form events are specific signals triggered by actions on form elements, like submitting, changing input values, or gaining/losing focus.

  1. How many events are there in JavaScript?

There are dozens of standard events, and developers can technically create custom events, so the number is potentially unlimited.

  1. What is event data in JavaScript?

Event data refers to information about the event that occurred, which is provided through an event object that's automatically passed to the event handler function.

  1. How to create event in JavaScript?

You don't directly create events; they are generated by the browser or system. Instead, you write event listeners to respond to those events when they happen.

  1. How to find JavaScript events?

You can find comprehensive lists and explanations of JavaScript events on resources like Mozilla Developer Network (MDN) or you can join a full stack development course on upGrad.

image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
advertise-arrow

upGrad Learner Support

Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.

2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.