JavaScript Events are actions or occurrences that happen in the browser. They can be triggered by various user interactions or by the browser itself.
HTML
<html>
<script>
function myFun() {
document.getElementById(
"gfg").innerHTML = "GeeksforGeeks";
}
</script>
<body>
<button onclick="myFun()">Click me</button>
<p id="gfg"></p>
</body>
</html>
- The onclick attribute in the <button> calls the myFun() function when clicked.
- The myFun() function updates the <p> element with id="gfg" by setting its innerHTML to "GeeksforGeeks".
- Initially, the <p> is empty, and its content changes dynamically on button click.
Event Types
JavaScript supports a variety of event types. Common categories include:
- Mouse Events: click, dblclick, mousemove, mouseover, mouseout
- Keyboard Events: keydown, keypress, keyup
- Form Events: submit, change, focus, blur
- Window Events: load, resize, scroll
Common JavaScript Events
Event Attribute | Description |
---|
onclick | Triggered when an element is clicked. |
onmouseover | Fired when the mouse pointer moves over an element. |
onmouseout | Occurs when the mouse pointer leaves an element. |
onkeydown | Fired when a key is pressed down. |
onkeyup | Fired when a key is released. |
onchange | Triggered when the value of an input element changes. |
onload | Occurs when a page has finished loading. |
onsubmit | Fired when a form is submitted. |
onfocus | Occurs when an element gets focus. |
onblur | Fired when an element loses focus. |
JavaScript
// Mouse Event
document.addEventListener("mousemove", (e) => {
console.log(`Mouse moved to (${e.clientX}, ${e.clientY})`);
});
// Keyboard Event
document.addEventListener("keydown", (e) => {
console.log(`Key pressed: ${e.key}`);
});
- The mousemove event tracks cursor movement.
- The keydown event captures key presses.
JavaScript Event Handlers
Event handlers can be used to handle and verify user input, user actions, and browser actions:
- Things that should be done every time a page loads
- Things that should be done when the page is closed
- Action that should be performed when a user clicks a button
- Content that should be verified when a user inputs data
- And more ...
Many different methods can be used to let JavaScript work with events:
- HTML event attributes can execute JavaScript code directly
- HTML event attributes can call JavaScript functions
- You can assign your own event handler functions to HTML elements
- You can prevent events from being sent or being handled
- And more ...
Event Handling Methods
1. Inline HTML Handlers
<button onclick="alert('Button clicked!')">Click Me</button>
2. DOM Property Handlers
let btn = document.getElementById("myButton");
btn.onclick = () => {
alert("Button clicked!");
};
3. addEventListener() (Preferred)
btn.addEventListener("click", () => {
alert("Button clicked using addEventListener!");
});
addEventListener() is the most versatile and recommended method as it supports multiple event listeners and removal of listeners.
Event Propagation
JavaScript events propagate in two phases:
JavaScript
document.querySelector("div").addEventListener("click", () => {
console.log("Div clicked");
}, true); // Capturing phase
button.addEventListener("click", (e) => {
console.log("Button clicked");
e.stopPropagation(); // Stops propagation
});
- Setting true in addEventListener makes it capture events during the capturing phase.
- stopPropagation() halts further propagation.
Event Delegation
Event delegation allows you to handle events efficiently by attaching a single listener to a parent element.
JavaScript
document.querySelector("ul").addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
console.log(`Clicked on item: ${e.target.textContent}`);
}
});
Events are delegated to list, reducing the need to add listeners to each list items.
Preventing Default Behavior
Certain elements have default actions (e.g., links navigating to URLs). Use preventDefault() to override them.
JavaScript
document.querySelector("a").addEventListener("click", (e) => {
e.preventDefault();
console.log("Link click prevented");
});
preventDefault() stops the link from navigating.
Practical Applications
HTML
<html>
<body>
<h2>Form Validation</h2>
<form id="example">
<input type="text" placeholder="Enter something" id="formInput" />
<button type="submit">Submit</button>
</form>
<script>
document.querySelector("#example").addEventListener("submit", (e) => {
let input = document.querySelector("#formInput");
if (!input.value) {
e.preventDefault();
alert("Input cannot be empty");
}
});
</script>
</body>
</html>
2. Dynamic Content
HTML
<html>
<body>
<h2>Dynamic Content</h2>
<button id="button">Add Element</button>
<script>
document.querySelector("#button").addEventListener("click", () => {
let newDiv = document.createElement("div");
newDiv.textContent = "New Element Added";
newDiv.style.margin = "10px 0";
document.body.appendChild(newDiv);
});
</script>
</body>
</html>
3. Interactive Lists
HTML
<html>
<body>
<h2>Interactive Lists</h2>
<ul id="lists">
<li>Interactive Item 1</li>
<li>Interactive Item 2</li>
<li>Interactive Item 3</li>
</ul>
<script>
let ul = document.querySelector("#lists");
ul.addEventListener("click", (e) => {
if (e.target.tagName === "LI") {
e.target.style.backgroundColor = "yellow";
}
});
</script>
</body>
</html>
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Decorators in Python In Python, decorators are a powerful and flexible way to modify or extend the behavior of functions or methods, without changing their actual code. A decorator is essentially a function that takes another function as an argument and returns a new function with enhanced functionality. Decorators are
10 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. Balance Factor = left subtree height - right subtree heightFor a Balanced Tree(for every node): -1 ⤠Balance Factor ⤠1Example of an
4 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
What is a Neural Network? Neural networks are machine learning models that mimic the complex functions of the human brain. These models consist of interconnected nodes or neurons that process data, learn patterns and enable tasks such as pattern recognition and decision-making.In this article, we will explore the fundamental
12 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read