-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
DOM Events are actions or occurrences that happen in the browser that JavaScript can detect and respond to. Examples include:
User interactions like click, mouseover, keypress
Browser actions like load, resize, scroll
Form actions like submit or change
DOM Events allow web pages to be interactive, dynamic, and responsive, enabling real-time user feedback.
Events are essential because they let you:
Respond to user interactions dynamically.
Validate form inputs before submission.
Create interactive elements like buttons, sliders, and menus.
Enhance user experience by providing instant feedback.
Control animations or visual changes based on user actions.
Without events, web pages would be static and unresponsive.
Mouse events detect pointer interactions with elements.
click – When an element is clicked.
dblclick – When double-clicked.
mouseover / mouseout – When the cursor enters or leaves an element.
mousemove – Tracks cursor movement over an element.
let btn = document.getElementById("clickBtn");
// Respond to click event
btn.addEventListener("click", () => {
alert("Button clicked!");
});
Keyboard events detect keypresses:
keydown – Triggered when a key is pressed down.
keyup – Triggered when a key is released.
keypress – Triggered while a key is being pressed.
document.addEventListener("keydown", (event) => {
console.log("Key pressed: " + event.key); // Logs pressed key
});
Form events detect changes in input and form submission:
submit – Triggered when a form is submitted.
change – Triggered when input value changes.
input – Triggered for every input change.
focus / blur – Triggered when an input gains or loses focus.
let form = document.getElementById("loginForm");
form.addEventListener("submit", (event) => {
event.preventDefault(); // Prevent actual submission
alert("Form submitted!");
});
Window events detect browser-level actions:
load – Triggered when the page finishes loading.
resize – Triggered when the browser window is resized.
scroll – Triggered when the user scrolls the page.
window.addEventListener("resize", () => {
console.log("Window width: " + window.innerWidth);
});
<button onclick="alert('Clicked!')">Click Me</button>
Harder to maintain.
Cannot easily attach multiple handlers.
addEventListener
(Recommended)let btn = document.querySelector("button");
btn.addEventListener("click", () => {
alert("Clicked using addEventListener!");
});
Cleaner and modular.
Supports multiple event listeners for the same element.
Every event passes an event object containing useful information:
document.addEventListener("click", (event) => {
console.log("Clicked element:", event.target); // Element clicked
console.log("X coordinate:", event.clientX); // Mouse X position
console.log("Y coordinate:", event.clientY); // Mouse Y position
});
Key properties of the event object:
target
– Element that triggered the event.
type
– Type of event.
clientX
/ clientY
– Mouse coordinates.
key
– Pressed key in keyboard events.
preventDefault()
– Stops default browser behavior.
Event starts at the target element and propagates up the DOM tree.
document.getElementById("child").addEventListener("click", () => {
alert("Child clicked!");
});
document.getElementById("parent").addEventListener("click", () => {
alert("Parent clicked!");
});
Clicking the child triggers both alerts (child first, then parent).
Event starts at the root and moves down to the target.
document.getElementById("parent").addEventListener(
"click",
() => { alert("Parent capturing!"); },
true // Capture phase
);
Using true
makes the parent handle the event before the child.
function handleClick() {
alert("Clicked!");
}
let btn = document.getElementById("clickBtn");
btn.addEventListener("click", handleClick);
// Later remove listener
btn.removeEventListener("click", handleClick);
Useful to prevent memory leaks or stop unwanted behavior.
<form id="signupForm">
<input type="text" name="username" placeholder="Username">
<input type="email" name="email" placeholder="Email">
<input type="submit" value="Register">
</form>
<div id="message"></div>
let form = document.getElementById("signupForm");
form.addEventListener("submit", (event) => {
event.preventDefault(); // Prevent form submission
let username = form.elements["username"].value;
let email = form.elements["email"].value;
let msg = document.getElementById("message");
if (username === "" || email === "") {
msg.textContent = "Please fill all fields!";
msg.style.color = "red";
} else {
msg.textContent = "Form submitted successfully!";
msg.style.color = "green";
}
});
Demonstrates form events, preventDefault, and dynamic user feedback.
Prefer addEventListener
over inline handlers.
Use event delegation for dynamically created elements.
Avoid attaching too many listeners to prevent performance issues.
Use preventDefault()
and stopPropagation()
when needed.
Always check the event target to ensure the correct element is handled.
DOM Events allow web pages to react to user actions and browser events. Key points:
Events include mouse, keyboard, form, and window events.
Use addEventListener
for clean, modular code.
The event object provides information about the action.
Understand event bubbling and capturing for proper event management.
Removing event listeners and using best practices ensures maintainable and efficient code.
Mastering DOM Events is essential for creating interactive, responsive, and dynamic web applications.
Create a button that displays an alert when clicked.
Add a mouseover
event to a <div>
that changes its background color, and revert it on mouseout
.
Use a keyboard event to log the key pressed by the user in the console.
Create a form and prevent its default submission using submit
event, then display the form data dynamically.
Attach a focus
and blur
event to an input field to highlight it when focused and remove the highlight when blurred.
Implement a resize
event that logs the current window width and height whenever the browser is resized.
Use event delegation to handle click events on multiple list items dynamically added to a <ul>
.
Attach a scroll
event to log the current scroll position of the page.
Create a dblclick
event on a paragraph that changes its text color when double-clicked.
Add a click event to a button that removes its own event listener after the first click.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts