Syllabus
Module – 2
Document Object Model: DOM Manipulation, Selecting Elements, Working with
DOM Nodes, Updating Element Content & Attributes, Events, Different Types of
Events, How to Bind an Event to an Element, Event Delegation, Event Listeners.
Text Book 1: Chapter: 5, 6
Document Object Model
As a browser loads a webpage, it creates a model of that page. This model is
called a DOM tree, and it is stored in the browser’s memory.
It consists of 04 Main types of the nodes
• Document Node
• Element Node
• Attribute Nodes
• Text Nodes
Document Object Model
Document Object Model
Document Object Model
Working with DOm
Working with Dom
Step 1: Access the Elements
DOM Query
A DOM Query refers to the process of selecting and retrieving elements from the
Document Object Model (DOM) using JavaScript. This is typically done using
various methods provided by the Document object.
Common DOM Query Methods:
➢ getElementById(id)
➢ getElementsByClassName(className)
➢ getElementsByTagName(tagName)
➢ querySelector(selector)
➢ querySelectorAll(selector)
getElementById(id)
getElementById(id) is a JavaScript method used to select an HTML element by its
id attribute. It belongs to the document object and returns the first element with
the specified id, or null if no such element exists.
Syntax:
[Link]("elementID");
<!DOCTYPE html>
<html lang="en">
<head>
<title>getElementById Example</title>
</head>
<body>
<p id="demo">Hello, World!</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
[Link]("demo").innerHTML = "Hello, JavaScript!";
}
</script>
</body>
</html>
getElementsByClassName(className)
The getElementsByClassName(className) method is a JavaScript function that
selects all elements with a specified class name.
It returns an HTMLCollection (a live collection of elements), which can be
accessed like an array.
Syntax:
[Link]("className");
"className": The name of the class to search for.
Returns an HTMLCollection of elements.
<!DOCTYPE html>
<html lang="en">
<head>
<title>getElementsByClassName Example</title>
</head>
<body>
<p class="message">Hello, World!</p>
<p class="message">Welcome to JavaScript!</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
let elements = [Link]("message");
for (let i = 0; i < [Link]; i++) {
elements[i].innerHTML = "Text Changed!";
}
}
</script>
</body>
</html>
getElementsByTagName(tagName)
• The getElementsByTagName(tagName) method is a JavaScript function that
selects all elements with a specified tag name.
• It returns an HTMLCollection (a live collection of elements) that can be accessed
like an array.
SYNTAX
[Link]("tagName");
"tagName": The name of the HTML tag to search for.
Returns an HTMLCollection of elements.
<!DOCTYPE html>
<html lang="en">
<head>
<title>getElementsByTagName Example</title>
</head>
<body>
<p>Hello, World!</p>
<p>Welcome to JavaScript!</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
let elements = [Link]("p");
for (let i = 0; i < [Link]; i++) {
elements[i].innerHTML = "Paragraph Changed!";
}
}
</script>
</body>
</html>
querySelector(selector)
The querySelector(selector) method is a modern and flexible way to select the first
matching element based on a CSS selector.
Syntax
[Link]("selector");
"selector": A CSS selector (e.g., tag, class, ID).
Returns the first matching element or null if none is found.
<!DOCTYPE html>
<html lang="en">
<head>
<title>querySelector Example</title>
</head>
<body>
<p class="message">Hello, World!</p>
<p class="message">Welcome to JavaScript!</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
let element = [Link](".message"); // Selects first element with class "message"
[Link] = "First paragraph changed!";
}
</script>
</body>
</html>
querySelectorAll(selector)
The querySelectorAll(selector) method selects all elements matching a given
CSS selector and returns a static NodeList (not live).
Syntax:
[Link]("selector");
"selector": A CSS selector (e.g., tag, class, ID).
Returns a NodeList of matching elements.
<!DOCTYPE html>
<html lang="en">
<head>
<title>querySelectorAll Example</title>
</head>
<body>
<p class="message">Hello, World!</p>
<p class="message">Welcome to JavaScript!</p>
<button onclick="changeText()">Click Me</button>
<script>
function changeText() {
let elements = [Link](".message"); // Selects all elements with class "message"
[Link]((element) => {
[Link] = "Paragraph changed!";
});
}
</script>
</body> </html>
Traversing the DOM in JavaScript
DOM (Document Object Model) traversal allows you to navigate between
elements in an HTML document using parent-child-sibling relationships.
<html> From the HTML above you can read:
<head> <html> is the root node
<title>DOM Tutorial</title> <html> has no parents
</head> <html> is the parent of <head> and <body>
<head> is the first child of <html>
<body> <body> is the last child of <html>
<h1>DOM Lesson one</h1>
<p>Hello world!</p> and:
</body>
<head> has one child: <title>
</html> <title> has one child (a text node): "DOM Tutorial"
<body> has two children: <h1> and <p>
<h1> has one child: "DOM Lesson one"
<p> has one child: "Hello world!"
<h1> and <p> are siblings
Traversing the DOM in JavaScript
Parent Node
In JavaScript, the parent node of an element can be accessed using the .parentNode
property. This property returns the immediate parent node of the specified element in
the DOM.
parentNode → Gets the parent element of a node.
parentElement → Similar to parentNode, but returns null if the parent is not an
element.
Traversing the DOM in JavaScript
Child Nodes Traversal
➢ childNodes: Returns a NodeList of all child nodes (including text nodes).
➢ children: Returns an HTMLCollection of only child elements.
➢ firstChild: Gets the first child node.
➢ firstElementChild: Gets the first child element.
➢ lastChild: Gets the last child node.
➢ lastElementChild: Gets the last child element.
Traversing the DOM in JavaScript
Sibling NodesTraversal
➢ nextSibling: Gets the next sibling node.
➢ nextElementSibling: Gets the next sibling element.
➢ previousSibling: Gets the previous sibling node.
➢ previousElementSibling: Gets the previous sibling element.
<script>
// Selecting the container
<!DOCTYPE html> let container = [Link]("container1");
<html lang="en">
<head> // Parent Node
<meta charset="UTF-8"> [Link]("Parent of container:", [Link]);
<meta name="viewport"
// Children of container
content="width=device-width, initial-
[Link]("Child Nodes:", [Link]); // Includes text nodes
scale=1.0">
[Link]("Children Elements:", [Link]); // Only elements
<title>DOM Traversal Example</title>
</head> // First and Last Child
<body> [Link]("First Child Node:", [Link]);
[Link]("First Element Child:", [Link]);
[Link]("Last Child Node:", [Link]);
<div id="container1">
[Link]("Last Element Child:", [Link]);
<p>First Paragraph</p>
<p>Second Paragraph</p> // Sibling Traversal
<p>Third Paragraph</p> let firstParagraph = [Link];
[Link]("Next Sibling:", [Link]);
[Link]("Next Element Sibling:", [Link]);
</div>
</script>
</body>
</html>
white space node in DOM
• In the Document Object Model (DOM), a white space node refers to a text node that
contains only whitespace characters, such as spaces, tabs, or newlines.
• These nodes can appear in various places in the DOM tree, especially when there are
spaces or line breaks between elements in the HTML source code.
Even though there are only two <p> elements inside the <div>, the
actual childNodes of the <div> might look like this:
Example
<div id="container"> 1.A text node (from the newline after <div>).
<p>First Paragraph</p> 2.A <p> element (First Paragraph).
<p>Second Paragraph</p> 3.A text node (from the space between <p> elements).
</div> 4.A <p> element (Second Paragraph).
5.A text node (from the newline before closing </div>).
white space node in DOM
How to Avoid White Space Nodes
Use .children instead of .childNodes.
children only returns element nodes, ignoring text nodes.
Trim White Space Nodes Manually
let elementsOnly = [Link]([Link]).filter(node => [Link]
!== 3 || [Link]());
[Link](elementsOnly); // Filters out whitespace nodes
nodeValue
The nodeValue property allows you to update the content of text nodes (not element
nodes). It is mainly used with Text Nodes and Comment Nodes.
OR
The nodeValue property in JavaScript is used to get or set the value of a text node or
comment node. It does NOT work directly on element nodes.
Syntax
[Link];
[Link] = "New Value";
Getting Text Node Value
<!DOCTYPE html>
<html lang="en">
<head>
<title>Get Node Value</title> Explanation:
</head> firstChild accesses the text node inside <p>.
<body>
nodeValue returns "Hello, World!".
<p id="myText">Hello, World!</p>
<script>
let para = [Link]("myText");
[Link]([Link]); // Output: "Hello, World!"
</script>
</body>
</html>
Updating Text Node Value
<!DOCTYPE html>
<html lang="en">
<head> Explanation:
<title>Set Node Value</title> firstChild gets the text node inside <p>.
</head>
<body> We update its nodeValue to "Text Updated!".
<p id="myText">Hello, World!</p>
<button onclick="updateText()">Change Text</button>
<script>
function updateText() {
let para = [Link]("myText");
[Link] = "Text Updated!";
}
</script>
</body>
</html>
nodeValue with Comment Nodes
<!DOCTYPE html>
<html lang="en">
<head> Explanation:
<title>Update Comment</title> childNodes[1] accesses the comment node.
</head>
<body>
<!-- This is a comment -->
nodeValue returns and updates the comment content.
<script>
let commentNode = [Link][1];
// Access comment
[Link]([Link]);
// Output: " This is a comment “
// Update comment text
[Link] = "Updated Comment!";
[Link]([Link]); // Output: "Updated Comment!"
</script>
</body>
</html>
get or set content inside an HTML element
In JavaScript, you can get or set content inside an HTML element using three main
properties:
➢ innerHTML → Gets/Sets HTML content (including tags).
➢ textContent → Gets/Sets only text (ignores HTML).
➢ innerText → Gets/Sets text, but respects hidden elements (display: none)
innerHTML
• innerHTML is a property of HTML elements in JavaScript that allows you
to get or set the HTML content inside an element.
• It is widely used for dynamically updating web pages by modifying an
element’s content.
Syntax
[Link]
Getting the value: Returns the HTML content as a string.
Setting the value: Replaces the current HTML content with new HTML.
Getting Inner HTML
<div id="myDiv">
<p>Hello, World!</p> Here, innerHTML retrieves the HTML content inside <div>.
</div>
<script>
let content = [Link]("myDiv").innerHTML;
[Link](content);
// Output: "<p>Hello, World!</p>"
</script>
Setting Inner HTML
<div id="myDiv">Original Text</div> This replaces "Original Text" with an <h2> element.
<script>
[Link]("myDiv").innerHTML = "<h2>New Heading</h2>";
</script>
textContent
The textContent property in JavaScript allows you to get or set the text content of an
element, without parsing it as HTML.
Unlike innerHTML, it treats everything as plain text, making it safer from Cross-Site
Scripting (XSS) attacks.
Syntax
[Link]
Getting text: Returns the text inside an element, including child elements.
Setting text: Replaces the existing text with new text.
Getting Text Content
<div id="myDiv">
<p>Hello, <span>World!</span></p>
</div>
textContent retrieves all the text, even if it's inside child elements.
<script>
let content = [Link]("myDiv").textContent;
[Link](content);
// Output: "Hello, World!"
</script>
Setting Text Content This replaces "Old Content" with "New Content".
<div id="myDiv">Old Content</div>
<script>
[Link]("myDiv").textContent = "New Content";
</script>
innerText
The innerText property in JavaScript allows you to get or set the visible text inside
an element.
Unlike textContent, it respects CSS styles such as display: none and does not
include hidden text.
Syntax
[Link]
• Getting text: Returns the visible text inside an element.
• Setting text: Replaces the existing text while keeping the element structure.
Getting Inner Text
<div id="myDiv">
<p>Hello, <span style="display:none;">Hidden</span> World!</p>
</div>
innerText ignores the hidden <span> due to display: none.
<script>
let text = [Link]("myDiv").innerText;
[Link](text); // Output: "Hello, World!"
</script>
Setting Inner Text
<div id="myDiv">Old Content</div> "Old Content" is replaced with "New Content".
<script>
[Link]("myDiv").innerText = "New Content";
</script>
createElement()
The [Link]() method is used to dynamically create new HTML
elements using JavaScript.
It allows you to add elements to the DOM without needing to modify existing HTML
code manually.
Syntax
[Link](tagName);
tagName – A string representing the type of element (e.g., "div", "p", "button").
Returns the newly created element, which is not yet added to the document.
Creating and Appending an Element
<div id="container"></div>
<script>
// Create a new <p> element
let newParagraph = [Link]("p");
// Add text content
[Link] = "This is a new paragraph!";
// Append it to the <div> with id "container"
[Link]("container").appendChild(newParagraph);
</script>
A new <p> element with text is added inside <div id="container">.
Creating a Button and Adding an Event Listener
<div id="buttonContainer"></div>
A button is added dynamically, and clicking it shows an alert.
<script>
// Create a new button element
let button = [Link]("button");
// Set button text
[Link] = "Click Me";
// Add a click event
[Link]("click", function() {
alert("Button Clicked!");
});
// Append button to the container
[Link]("buttonContainer").appendChild(button);
</script>
Creating a List of Items
<ul id="listContainer"></ul>
<script>
let ul = [Link]("listContainer");
for (let i = 1; i <= 3; i++) {
Removing an Element
let li = [Link]("li");
[Link] = "Item " + i; To remove an element after creating it:
[Link](li);
} [Link]("my-paragraph").remove();
</script>
A <ul> with 3 <li> items (Item 1, Item 2, Item 3) is created.
createTextNode()
A Text Node in JavaScript represents plain text within the DOM. Unlike an element
node (e.g., <p>, <div>), a text node only contains text and doesn't have attributes or child
elements.
We use [Link]() to create a text node.
Steps involved
➢ Select the Parent Element
➢ Create a Text
➢ Append the Text
<!DOCTYPE html>
<html lang="en">
<head>
<title>Text Node Example</title>
</head>
<body>
<div id="container"></div> <!-- Empty div where we will add text -->
<p id="textElement">Original text</p>
<script>
// Step 1: Select the parent element
let container = [Link]("container");
// Step 2: Create a text node
let textNode = [Link]("Hello, this is a dynamically created text node!");
// Step 3: Append the text node to the parent element
[Link](textNode);
//Modifying an Existing Text Node
let textElement = [Link]("textElement").firstChild;
[Link] = "This is the updated text!";
</script>
</body> ]
</html>
appendChild()
The appendChild() method is used to add (or append) a child node to a parent node
in the DOM. This is commonly used to add elements or text nodes dynamically.
Syntax
[Link](childNode);
[Link](child1, child2, "Some text"); Multiple childs
parentNode → The element to which you want to add a child.
childNode → The node (element or text) that will be appended.
appendChild()
Example <script>
<!DOCTYPE html> let container =
<html lang="en"> [Link]("container");
let p1 = [Link]("p");
<head> [Link] = " Added Paragraph 1";
<title>Document</title>
</head> let p2 = [Link]("p");
<body> [Link] = "Added Paragraph 2";
<div id="container">
[Link](p1, p2, "This is some additional
<p> First Paragraph </p> text.");
</div> </script>
</body>
</html>
removeChild()
The removeChild() method is used to remove a child node from a parent node in the
DOM.
Syntax
[Link](childNode);
or
[Link]("myElement").remove();
parentNode → The parent element containing the child.
childNode → The child element to be removed.
<div id="imageContainer">
<img id="myImage" src="[Link] alt="Sample Image">
</div>
<button onclick="removeImage()">Remove Image</button>
<script>
function removeImage() {
let container = [Link]("imageContainer");
let image = [Link]("myImage");
if (image) {
[Link](image);
}
}
</script>
[Link]() method
The [Link]() method is used <!DOCTYPE html>
to write content directly into the <html lang="en">
HTML document. <head>
<title>[Link]() Example</title>
It can be useful for quickly displaying </head>
text, but it has significant limitations, <body>
especially in modern web
development. <script>
[Link]("<h1>Hello, World!</h1>");
[Link]("<p>This text is added using
[Link]().</p>");
Syntax </script>
[Link]("Hello, world!");
</body>
</html>
Attribute related Methods
We can use either id or class name
➢ getAttribute()
➢ hasAttribute()
➢ setAttribute()
➢ removeAttribute()
getAttribute() method
The getAttribute() method is used to retrieve the value of a specified attribute from
an HTML element.
Syntax
[Link](attributeName);
element → The HTML element from which you want to get the attribute value.
attributeName → The name of the attribute you want to retrieve (e.g., "id", "href",
"src").
getAttribute() method
Example
<input id="myInput" type="password">
<button onclick="getInputType()">Get Input Type</button>
<script>
function getInputType() {
let input = [Link]("myInput");
let typeValue = [Link]("type");
alert("Input type is: " + typeValue);
}
</script>
hasAttribute() method
The hasAttribute() method checks whether a specific attribute exists on an HTML
element. It returns true if the attribute is present and false if it is missing.
Syntax
[Link]("attributeName");
element → The HTML element to check.
attributeName → The name of the attribute you want to verify.
Returns true if the attribute exists, otherwise false.
setAttribute() method
The setAttribute() method is used to add a new attribute or modify an existing attribute
on an HTML element.
Syntax
[Link]("attributeName", "value");
element → The HTML element to modify.
attributeName → The name of the attribute to add or change (e.g., "id", "href", "class").
value → The new value for the attribute.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<input id="passwordField" type="password">
<button onclick="showPassword()">Show Password</button>
<script>
function showPassword() {
let input = [Link]("passwordField");
[Link]("type", "text"); // Change password field to text
}
</script>
</body> </html>
removeAttribute() method
The removeAttribute() method removes a specified attribute from an HTML
element.
Syntax
[Link]("attributeName");
element → The HTML element from which you want to remove an attribute.
attributeName → The name of the attribute to remove (e.g., "id", "class",
"disabled").
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<a id="myLink" href="[Link] Here</a>
<button onclick="removeLink()">Remove Link</button>
<script>
function removeLink() {
let link = [Link]("myLink");
[Link]("href"); // Removes the href attribute
alert("The link attribute has been removed.");
}
</script>
</body>
</html>
EVENTS
In JavaScript, events are actions or occurrences that happen in the browser, often
triggered by the user.
JavaScript allows you to interact with these events, responding to actions like clicking
a button, submitting a form, or loading a page.
Different Types of Events
➢ UI Events
➢ Keyboard Events
➢ Mouse Events
➢ Focus Events
➢ Form Events
➢ Mutation Events
How Event Trigger Works
Event Object
• All event listeners receive an event object with useful data.
Event Flow (Bubbling vs Capturing)
Events go through three phases:
– Capture phase (from window down to the element)
– Target phase (the actual target element)
– Bubble phase (back up to window)
Default is bubbling, but you can listen during capture
Mouse Events in JavaScript
Mouse events are triggered by user interactions with the mouse (or similar devices like
touchpads). JavaScript allows you to handle these events using event listeners.
Event Description
click Fires when an element is clicked.
dblclick Fires when an element is double-clicked.
mousedown Fires when a mouse button is pressed down.
mouseup Fires when a mouse button is released.
mousemove Fires when the mouse pointer is moving over an element.
mouseenter Fires when the pointer enters the element (does NOT bubble).
mouseleave Fires when the pointer leaves the element (does NOT bubble).
mouseover Fires when the pointer moves onto an element or its children (bubbles).
mouseout Fires when the pointer moves out of an element or its children (bubbles).
contextmenu Fires when the right mouse button is clicked (shows context menu).
Adding Mouse Event Listeners
const box = [Link]('box');
// Click
[Link]('click', function(event) {
[Link]('Clicked!', event);
});
Event Object Properties
When a mouse event occurs, the event handler receives an event object (MouseEvent) with
useful properties:
Mouse Tracker
<div id="tracker" style="width: 300px; height: 200px; border: 1px solid black;">
Move your mouse here
</div>
<script>
const tracker = [Link]('tracker');
[Link]('mousemove', (e) => {
[Link] = `Mouse at (${[Link]}, ${[Link]})`;
});
</script>
Keyboard Events in JavaScript
Keyboard events are fired when the user interacts with the keyboard. These events help
you capture and respond to key presses in forms, games, shortcuts, etc.
Syntax
[Link]('keydown', function(event) {
[Link]('Key down:', [Link]);
});
Example
<input id="myInput" placeholder="Type something and press Enter" />
<script>
const input = [Link]('myInput');
[Link]('keydown', function(e) {
if ([Link] === 'Enter') {
alert('You pressed Enter!');
}
});
</script>
Form Events in JavaScript
Common Form Events
Event Fired When...
submit A form is submitted
reset A form is reset
change An element loses focus and its value has changed
input When the value of an element is changed (live typing)
focus An element gains focus
blur An element loses focus
submit Event Example
<form id="myForm">
<input type="text" name="name" required />
<button type="submit">Submit</button>
</form>
<script>
const form = [Link]('myForm');
[Link]('submit', function(e) {
[Link](); // Prevent actual submission
alert('Form submitted!');
});
</script>
Form Events in JavaScript
Useful Methods and Properties
Property/Method Description
[Link] Returns a collection of form elements
[Link]() Resets all fields to default values
[Link]() Submits the form programmatically
[Link] Gets/sets the value of an input
[Link]() Returns true if the form is valid
focus and blur Example reset Event Example
const input = [Link]('input');
const form = [Link]('form');
[Link]('focus', () => {
[Link]('Input is focused'); [Link]('reset', () => {
}); [Link]('Form was reset');
});
[Link]('blur', () => {
[Link]('Input lost focus');
});
Validating a Form
[Link]('submit', function(e) {
if (![Link]()) {
[Link](); // Stop submission if invalid
alert('Please fill out all required fields.');
}
});
Focus Events in JavaScript
Focus events deal with when elements receive or lose focus
Core Focus Events
Event Triggered When... Bubbles?
focus An element receives focus ❌ No
blur An element loses focus ❌ No
focusin Like focus, but does bubble ✅ Yes
focusout Like blur, but does bubble ✅ Yes
Focus Events in JavaScript
focus and blur
• These do not bubble, so they must be used directly on the target element or with
addEventListener.
Example
const input = [Link]("input");
[Link]("focus", () => {
[Link]("Input focused");
});
[Link]("blur", () => {
[Link]("Input lost focus");
});
Focus Events in JavaScript
focusin and focusout
These do bubble, so they’re useful for event delegation.
Example
const form = [Link]("form");
[Link]("focusin", (e) => {
[Link]("Focused on:", [Link]);
});
[Link]("focusout", (e) => {
[Link]("Blurred from:", [Link]);
});
Mutation Events
Mutation events were introduced in the DOM Level 2 Events specification to allow
developers to detect and respond to changes in the DOM tree structure, attributes, or
text content.
They could detect when:
– A node is added or removed
– Attributes are modified
– Text content is changed
Mutation Events
List of Mutation Events
Event Name Triggered When...
DOMSubtreeModified Any change occurs in the subtree of an element
DOMNodeInserted A new node is inserted into the DOM
DOMNodeRemoved A node is removed from the DOM
A node is inserted into the document (from
DOMNodeInsertedIntoDocument
outside)
DOMNodeRemovedFromDocument A node is removed from the document
DOMAttrModified An attribute is added, changed, or removed
DOMCharacterDataModified Text inside a text node or comment is changed
Mutation Events
EXAMPLE
const el = [Link]("test");
[Link]("DOMNodeInserted", (e) => {
[Link]("Node inserted:", [Link]);
});
[Link]("DOMAttrModified", (e) => {
[Link](`Attribute ${[Link]} modified from ${[Link]} to ${[Link]}`);
});
Mutation Events
Why Mutation Events Are DeprecatedMutation events were found to have
significant downsides, especially in large, dynamic applications.
Problems:
Performance: They're synchronous and fire immediately on DOM changes,
blocking the main thread.
Unpredictable behavior: Triggers too often, sometimes unnecessarily.
Limited control: You can't filter which changes you're interested in efficiently.
Window Events/UI EVENTS
Window events are events that occur on the window object — representing the browser window or tab.
These are used to detect things like page load, unload, resizing, scrolling, and more.
Event Triggered When...
load All page resources (images, scripts, etc.) are loaded
DOMContentLoaded HTML is fully parsed (no need to wait for styles/images)
resize Browser window is resized
scroll User scrolls the page
beforeunload User is about to leave or reload the page
unload Page is being unloaded (deprecated in most cases)
error A JavaScript error or resource loading issue occurs
focus / blur Window gains or loses focus
hashchange The URL hash changes (e.g., #section1)
popstate User navigates using the browser’s back/forward buttons
visibilitychange Document tab is hidden or shown
Example: resize
[Link]("resize", () => {
[Link]("Window resized to", [Link], "x", [Link]);
});
Example: scroll
[Link]("scroll", () => {
[Link]("Scroll position:", [Link]);
});
Example Error
[Link]("error", (e) => {
[Link]("JS error:", [Link], "at", [Link], [Link]);
});
Example: load and DOMContentLoaded
// Runs after the entire page (including images) is loaded
[Link]("load", () => {
[Link]("Everything loaded");
});
// Runs when the DOM is ready (faster, doesn't wait for images)
[Link]("DOMContentLoaded", () => {
[Link]("DOM fully loaded and parsed");
});
Event Listener
An event listener is a function that waits for a specific event (like a click or key
press) to happen on a particular element. When the event occurs, the function is
executed.
Syntax
[Link](event, listener, options);
Parameters:
event: The event name as a string ('click', 'keydown', 'submit', etc.)l
istener: The function to run when the event happensoptions
(optional): An object or boolean that controls advanced behavior
Example
Single EventListener
const button = [Link]('button');
[Link]('click', function () {
alert('Button clicked!');
});
Multiple Event Listeners
[Link]('click', () => [Link]('First'));
[Link]('click', () => [Link]('Second'));
Removing Event Listeners
const handleClick = () => alert('Clicked');
[Link]('click', handleClick);
[Link]('click', handleClick);
Event Object
When an event occurs (like a click, keypress, etc.), JavaScript automatically
passes an event object to the event handler.
This object contains information about the event, like what triggered it, where
it happened, key/button pressed, and more.
Example
[Link]('click', function (event) {
[Link](event); // Logs the event object
});
You can name it anything (event, e, evt, etc.), but e is common.
Event Object
Common Properties
Property/Method Description
type The event type (e.g. 'click', 'keydown')
target The element that triggered the event
currentTarget The element the event listener is attached to
timeStamp The time (in ms) since page load when event occurred
defaultPrevented true if preventDefault() was called
Event Object
Event Propagation Control
Method Description
stopPropagation() Stops the event from bubbling up
stopImmediatePropagation() Stops all further listeners (same element) from firing
Cancels the default behavior (e.g., following a link,
preventDefault()
submitting a form)
Example
[Link]('click', function(e) {
[Link]('target:', [Link]); // clicked element
[Link]('currentTarget:', [Link]); // parent
});
Event Delegation
Event Delegation is a technique where a single event listener is added to a parent
element, and it handles events triggered by its child elements through event
bubbling.
Instead of attaching individual listeners to each child (which can be inefficient), you
"delegate" the event to a common ancestor.
Why Use Event Delegation?
• Performance: One listener instead of many
• Dynamic content: Works even for elements added later (after page load)
• Cleaner code: Centralized control
Event Delegation
How It Works (Behind the Scenes)
• JavaScript events bubble up from the event target (where it happened) to its
ancestors.
<li> → <ul> → <body> → <html> → document
So if you click on an <li>, the event travels up through its parent nodes. You can catch it
at any point.
<!DOCTYPE html> <script>
<html lang="en">
<head>
const menu = [Link]('menu');
<title>Document</title>
</head> [Link]('click', function (e) {
<body> if ([Link] === 'LI') {
<ul id="menu"> alert(`You clicked on ${[Link]}`);
<li>Home</li> }
});
<li>About</li>
<li>Contact</li> </script>
</ul>
</body>
</html>