For working professionals
For fresh graduates
More
JavaScript Tutorial Concepts -…
1. Introduction to JavaScript
2. JavaScript Examples
3. Applications of JavaScript
4. JavaScript Hello World
5. JavaScript let
6. JavaScript Callbacks
7. JavaScript Arrays
8. JavaScript Array reduce()
9. JavaScript Loops
10. JavaScript Objects
11. DOM Model in JavaScript
12. JavaScript Form Validation
13. JavaScript Games
14. JavaScript Promises
15. JavaScript Async Await
16. JavaScript Closure
17. JavaScript this keyword
18. OOP in JavaScript
19. Operators in Javascript
20. Redirect in JavaScript
21. Express JS
22. Convert String to int in JavaScript
23. JavaScript Functions
24. JavaScript New Lines
25. JavaScript Regex
26. JavaScript Events
Now Reading
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.
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.
Let us learn about the essential JavaScript event types with the help of this JavaScript events list with examples of some of the events.
There are two primary ways to handle events in JavaScript. Let us learn about them both in this JavaScript event tutorial.
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>
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.
Let us now explore some working examples of JavaScript events.
<!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!".
<!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).
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">×</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
Here are some more JavaScript events with examples:
<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>
<!DOCTYPE html>
<html>
<head>
<h1>Event Example</h1>
</head>
<body onload="alert('Page finished loading!')">
</body>
</html>
Let us now learn about JavaScript events in more detail.
When an event fires, an event object is automatically passed to your event handler function. This object carries rich information about the event:
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() 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 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
}
});
Now that we have reached this point, I want you to try these out yourself:
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.
JavaScript events are signals that notify your code about user interactions, browser actions, or other occurrences on a webpage.
JavaScript form events are specific signals triggered by actions on form elements, like submitting, changing input values, or gaining/losing focus.
There are dozens of standard events, and developers can technically create custom events, so the number is potentially unlimited.
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.
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.
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.
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
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.