0% found this document useful (0 votes)
12 views

Module-2

The document provides an overview of the Document Object Model (DOM) in web development, detailing its structure, features, and methods for manipulating HTML elements. It covers various ways to access and modify DOM elements using JavaScript, including methods for adding, removing, and updating elements dynamically. Additionally, it discusses traversing the DOM and best practices for manipulating content to enhance user experience.

Uploaded by

umeshm_m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Module-2

The document provides an overview of the Document Object Model (DOM) in web development, detailing its structure, features, and methods for manipulating HTML elements. It covers various ways to access and modify DOM elements using JavaScript, including methods for adding, removing, and updating elements dynamically. Additionally, it discusses traversing the DOM and best practices for manipulating content to enhance user experience.

Uploaded by

umeshm_m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 106

1

Document Object Model


(DOM)
Module 2

CS380
Document Object Model
2
(DOM)
 <html>
 <head>
<title>JavaScript DOM</title>
 </head>
 <body>
 <h1>Hello DOM!</h1>
 </body>
 </html>

CS380
Document Object Model
3
(DOM)
Document Object Model
4
(DOM)
 It is a structure of HTML elements which
are converted to objects(nodes)
 All these objects are arranged in tree
data Structure
 HTML page loading( html elements --
objects)
 This tree structure we call it as DOM

CS380
Document Object Model
5
(DOM)
 Features of DOM
1. Accessing HTML Elements
2. Modifying Content Dynamically

3. Handling User Events

4. Creating and Deleting Elements

5. Dynamic Content Loading

6. Enhancing User Experience

CS380
Document Object Model
6
(DOM)
 Why DOM is created.
 Using JS we can manipulate HTML
document so that we can provide
dynamic user content
 DOM manipulation
 How to access any DOM node(html
element)
 How to add new html elements

 How to remove html elements

 How to change content or attributes of

CS380 html elements.


Access HTML Elements in
7
JavaScript
 1. Accessing by ID
 Selects a single element with a specific id.
 Returns an element object.
 Commonly used when an element has a unique
ID.
 Example:
 <p id="demo">Hello, World!</p>
 <script>

 let element =
document.getElementById("demo");
 element.style.color = "blue";
 </script>
CS380
Access HTML Elements in
8
JavaScript
 2. Accessing by Class Name
 Selects multiple elements with the same class.
 Returns an HTMLCollection (array-like object).
 Can loop through elements to apply changes.
 <p class="myClass">Paragraph 1</p>
 <p class="myClass">Paragraph 2</p>
 <script>
 let elements =
document.getElementsByClassName("myClass");
 for (let i = 0; i < elements.length; i++) {
 elements[i].style.color = "green";
 }
 </script>

CS380
Access HTML Elements in
9
JavaScript
 3. Accessing by Tag Name
 Selects all elements of a specific tag.
 Returns an HTMLCollection.
 Useful for bulk modifications.
 <p>First Paragraph</p>
 <p>Second Paragraph</p>
 <script>
 let elements = document.getElementsByTagName("p");
 for (let i = 0; i < elements.length; i++) {
 elements[i].style.fontSize = "20px";
 }
 </script>

CS380
Access HTML Elements in
10
JavaScript
 4. Accessing by Query Selector (First
Match)
 Selects the first element that matches the given
CSS selector.
 Returns a single element.
 More flexible than getElementById.

 <p class="myClass">First Paragraph</p>


 <p class="myClass">Second Paragraph</p>

 <script>

 let element =
document.querySelector(".myClass");
CS380
 element.style.fontWeight = "bold";
Access HTML Elements in
11
JavaScript
 5. Accessing by Query Selector (All Matches)
 Selects all elements matching a CSS selector.
 Returns a NodeList (similar to an array).
 Can use forEach to iterate over elements.
 <p class="myClass">First Paragraph</p>
 <p class="myClass">Second Paragraph</p>
 <script>
 let elements = document.querySelectorAll(".myClass");
 elements.forEach(element => {
 element.style.backgroundColor = "yellow";
 });
 </script>

CS380
Selecting Elements by
12
Attribute Name
 1. Selecting Elements by Attribute
Name (hasAttribute())
 ✔ Use getElementsByTagName() to get all
elements of a specific tag.
 ✔ Loop through the elements and use
hasAttribute("attribute-name") to check if
the attribute exists.
 ✔ Useful when you need to find an element
with a specific attribute but without
knowing its value.

CS380
Selecting Elements by
13
Attribute Name
 2. Selecting Elements by Attribute
Value (getAttribute())
 ✔ Use getElementsByTagName() to get all
elements.
 ✔ Use getAttribute("attribute-name") to
compare an attribute's value.
 ✔ Stops at the first match (using break) to
improve efficiency.
 ✔ Useful when you need to find an element
with a specific attribute value.
CS380
Selecting Elements by
14
Attribute Name
 3. Selecting Elements by Partial
Attribute Value (includes())
 ✔ Use getAttribute("attribute-name") and
check if it contains a specific keyword.
 ✔ includes("value") helps filter attributes
dynamically.
 ✔ Useful when attribute values are dynamic
or partially match a keyword.
 ✔ Stops after finding the first match for
performance optimization.
CS380
Traversing the DOM
15

 1. Parent Node (parentNode)


 ✔ Used to access the parent of an
element.
 ✔ Moves one level up in the DOM
hierarchy.

CS380
Traversing the DOM
16

 2. First Child (firstChild)


 ✔ Selects the first child node of an
element.
 ✔ Can include text nodes (spaces,
newlines).
 ✔ Use firstElementChild to avoid
selecting text nodes.

CS380
Traversing the DOM
17

 3. Last Child (lastChild)


 ✔ Selects the last child node of an
element.
 ✔ Can include text nodes (use
lastElementChild for elements only).

CS380
Traversing the DOM
18

 4. Next Sibling (nextSibling)


 ✔ Selects the next node after an
element.
 ✔ Can include text nodes (use
nextElementSibling for elements only).

CS380
Traversing the DOM
19

 5. Previous Sibling (previousSibling)


 ✔ Selects the previous node before an
element.
 ✔ Can include text nodes (use
previousElementSibling for elements
only).

CS380
Accessing and Updating
20
text
 Accessing and Updating Using
 nodeValue,
 innerText, and
 innerHTML

CS380
Accessing and Updating
21
text
 Accessing and Updating Using
 nodeValue,
 innerText, and
 innerHTML

CS380
1. nodeValue
22

 ✔ Used to get or change the value of a


text node.
 ✔ Access text content inside a text node
(textContent).
 ✔ Must use firstChild or childNodes[0] to
access the text node.

CS380
23
 <!DOCTYPE html>
 <html>
 <body>
 <p id="demo">Hello, World!</p>
 <button onclick="changeNodeValue()">Click Me</button>

 <script>
 function changeNodeValue() {
 document.getElementById("demo").firstChild.nodeValue =
"Welcome ISE";
 }
 </script>
 </body>
 </html>

CS380
2. innerText
24

 ✔ Used to get or set only the visible text


inside an element.
 ✔ Ignores hidden or formatted HTML
content.
 ✔ Faster than innerHTML since it only
deals with text.

CS380
25
 <!DOCTYPE html>
 <html>
 <body>

 <p id="demo">Hello, <span style="display: none;">Hidden</span>


World!</p>
 <button onclick="changeInnerText()">Click Me</button>

 <script>
 function changeInnerText() {
 document.getElementById("demo").innerText = "Welcome
ISE";
 }
 </script>

CS380
 </body>
3. innerHTML
26

 ✔ Used to get or set HTML content inside


an element.
 ✔ Allows adding HTML elements like
<b> and <i> dynamically.
 ✔ Should be used cautiously to prevent
security risks (e.g., XSS attacks).

CS380
27
 <!DOCTYPE html>
 <html>
 <body>
 <p id="demo">Hello, World!</p>
 <button onclick="changeInnerHTML()">Click Me</button>
 <script>
 function changeInnerHTML() {
 document.getElementById("demo").innerHTML =
"<b>Welcome ISE</b>";
 }
 </script>

 </body>
 </html>
CS380
Adding HTML Elements
28

 DOM Manipulations
 createElement()
 createTextNode()
 appendChild()

 innerHTML

CS380
Using DOM Manipulations
29

 1. Using document.createElement()
 ✔ Creates a new HTML element
dynamically.
 ✔ Uses appendChild() to add it to the
document.
 ✔ Useful for adding elements based on
user actions.

CS380
30

 2.Using createTextNode()
 ✔ Uses createTextNode() to create a text
node separately and append it to <p>.

CS380
 <!DOCTYPE html>
 <html>
31  <body>
 <p>Hello, World!</p>
 <button onclick="addElement()">Click Me</button>
 <script>
 function addElement() {
 let newPara = document.createElement("p");
 let textNode =
document.createTextNode("Welcome ISE"); // Create
text node
 newPara.appendChild(textNode); // Append text
to <p>
 document.body.appendChild(newPara); // Append
<p> to body
 }
CS380
 </script>
32
 <!DOCTYPE html>
 <html>
 <body>
 <p>Hello, World!</p>
 <button onclick="addElement()">Click Me</button>
 <script>
 function addElement() {
 let newPara = document.createElement("p");
 newPara.innerHTML = "Welcome ISE";
 document.body.appendChild(newPara); // Append to
body
 }
 </script>
 </body>
CS380

33

 Using insertBefore()
 ✔ Inserts a new element before an
existing one.
 ✔ Requires a reference node and its
parent node.

CS380
 <!DOCTYPE html>
 <html>
34
 <body>

 <p id="existing">Hello, World!</p>


 <button onclick="insertElement()">Click Me</button>

 <script>
 function insertElement() {
 let newPara = document.createElement("p");
 newPara.innerHTML = "Welcome ISE";
 let parent = document.body;
 let existingPara =
document.getElementById("existing");
 parent.insertBefore(newPara, existingPara);

CS380 }
 </script>
Using innerHTML
35

 ✔ Directly adds new HTML elements


inside an element.
 ✔ Faster, but overwrites existing content
if not used carefully.

CS380
36

 <!DOCTYPE html>
 <html>
 <body>

 <p id="target">Hello, World!</p>


 <button onclick="addUsingInnerHTML()">Click
Me</button>

 <script>
 function addUsingInnerHTML() {
 document.body.innerHTML += "<p>Welcome
ISE</p>";

CS380 }
 </script>
Removing HTML Elements
37

 When to Use Each Method?


 🔹 removeChild() → Best when you need
to remove a specific child from a known
parent.
 🔹 remove() → Simple and direct removal
for modern browsers.
 🔹 innerHTML = "" → Clears all content
inside an element .

CS380
38

 1. Using removeChild()
 ✔ Removes a specific child element from
its parent.
 ✔ Requires both the parent element and
the child element.

CS380
39
 <!DOCTYPE html>
 <html>
 <body>
 <p id="para">Hello, World!</p>
 <button onclick="removeElement()">Click Me</button>
 <script>
 function removeElement() {
 let parent = document.body;
 let child = document.getElementById("para");
 parent.removeChild(child); // Remove the <p> element
 }
 </script>
 </body>
CS380
 </html>
40

 2. Using remove() (Simpler Method)


 ✔ Directly removes an element without
needing the parent.
 ✔ Works on modern browsers
(removeChild() is safer for older ones).

CS380
41

 <!DOCTYPE html>
 <html>
 <body>
 <p id="para">Hello, World!</p>
 <button onclick="removeElement()">Click Me</button>
 <script>
 function removeElement() {
 document.getElementById("para").remove(); //
Directly remove <p>
 }
 </script>
 </body>
 </html>
CS380
42

 3. Using innerHTML (Clearing All


Elements)
 ✔ Removes all content inside an element
by setting innerHTML to an empty string.
 ✔ Use carefully, as it deletes all children
of the selected element.

CS380
43
 <!DOCTYPE html>
 <html>
 <body>
 <p>Hello, World!</p>
 <p>Welcome to ISE</p>
 <button onclick="clearBody()">Click Me</button>
 <script>
 function clearBody() {
 document.body.innerHTML = ""; // Clears entire body
content
 }
 </script>
 </body>
 </html>
CS380
Adding and Removing
44
Attributes Using JavaScript
 ✔ Use setAttribute() to add/modify
attributes.
 ✔ Use removeAttribute() to remove
attributes.

CS380
Adding Attributes
45

 ✔ Use setAttribute(attribute, value) to


add or modify an attribute.
 ✔ Directly assign using element.attribute
= value.

CS380
46

 <!DOCTYPE html>
 <html>
 <body>
 <button id="btn" onclick="addAttribute()">Click
Me</button>
 <script>
 function addAttribute() {
 let btn = document.getElementById("btn");
 btn.setAttribute("disabled", "true"); // Adds
'disabled' attribute
 }
 </script>
 </body>
CS380
 </html>
Removing an Attribute
47

 <!DOCTYPE html>
 <html>
 <body>
 <button id="btn" disabled
onclick="removeAttribute()">Click Me</button>
 <script>
 function removeAttribute() {
 let btn = document.getElementById("btn");
 btn.removeAttribute("disabled"); // Removes
'disabled' attribute
 }
 </script>
 </body>
CS380
 </html>
Updating HTML Content
48

 Using document.write()
 ✔ document.write() replaces the entire

page content if called after the page has


loaded.
 ✔ Only use it while the page is loading,

otherwise, it erases existing content.


 ✔ Not recommended for dynamic

updates (use innerHTML instead).


 ✅ When the button is clicked, everything

disappears, and only "Welcome ISE"


CS380
remains.
49

 <!DOCTYPE html>
 <html>
 <body>
 <p>Hello, World!</p>
 <button onclick="updateContent()">Click Me</button>
 <script>
 function updateContent() {
 document.write("Welcome ISE"); // Overwrites
everything
 }
 </script>
 </body>
 </html>
CS380
document.write() While
50
Loading
 This does not erase existing content since it's called during
page load.
 <!DOCTYPE html>
 <html>
 <body>
 <script>
 document.write("<p>Welcome ISE</p>"); // Adds a
new paragraph
 </script>
 </body>
 </html>
 ✅ This works safely because document.write() is used while
the page is being loaded.
CS380
51

 ⚠ Why document.write() is Not


Recommended for Updates?
 🔹 If called after the page loads, it erases
everything on the page.
 🔹 Use innerHTML or textContent instead
for dynamic updates.

CS380
Events in JavaScript
52

 Events are actions or occurrences that


happen in the browser, which JavaScript
can detect and respond to.
 For example, clicking a button, pressing
a key, or loading a page.
 When an event has occurred, it is often
described as having fired or been
raised.
 Events are said to trigger a function or
script.
CS380
1️⃣Importance of Events
53

 ✔ Allow interaction between user and


web page.
 ✔ Enable dynamic content updates.
 ✔ Trigger functions based on user
actions.

CS380
2️⃣Common Event Types
54

 ✔ Mouse Events: click, dblclick,


mouseover, mouseout.
 ✔ Keyboard Events: keydown, keyup,
keypress.
 ✔ Form Events: submit, change, focus,
blur.
 ✔ Window Events: load, resize, scroll.

CS380
Events
55

CS380
Events
56

CS380
Events
57

CS380
Events
58

CS380
Events
59

CS380
HOW EVENTS TRIGGER JS
60
CODE
 When the user interacts with the HTML
on a web page,
 there are three steps involved in getting
it to trigger some JavaScript code.
 Together these steps are known as
event handling.

CS380
HOW EVENTS TRIGGER JS
61
CODE
 1️⃣Selecting Elements
 ✔ Identify the HTML element(s) to respond
to (e.g., link, button, form).
 ✔ Use DOM queries like getElementById(),
getElementsByClassName(), etc.
 ✔ Browser-specific events (e.g., page load,
scroll) work with the window object.

CS380
HOW EVENTS TRIGGER JS
62
CODE
 2️⃣Binding Events
 ✔ Specify which event should trigger the
code (e.g., click, mouseover, submit).
 ✔ Attach events to DOM nodes (elements).
 ✔ Some events work with all elements
(e.g., mouseover), while others are
element-specific (e.g., submit for forms).

CS380
HOW EVENTS TRIGGER JS
63
CODE
 3️⃣Defining Event Handlers
 ✔ Provide the code (function) to run when
the event occurs.
 ✔ Can be a named function or an
anonymous function.
 ✔ Example: Changing text when a button is
clicked.

CS380
HOW EVENTS TRIGGER JS
64
CODE
 <!DOCTYPE html>
 <html>
 <body>
 <p id="text">Hello, World!</p>
 <button onclick="changeText()">Click Me</button>

 <script>
 function changeText() {
 document.getElementById("text").innerHTML = "Welcome
ISE";
 }
 </script>
 </body>
 </html>
CS380
3 Ways to Bind an Event to an
Element
65

 1️⃣HTML Event Handlers (Old Method -


Not Recommended)
 Event handling done via attributes in
HTML tags.
 Poor practice because it mixes HTML
with JavaScript.
 Limited control and difficult to manage.

CS380
3 Ways to Bind an Event to an
Element
66

 <a onclick="hide()">Click Me</a>


 <script>
 function hide() {
 alert("Link Clicked!");
 }
 </script>

CS380
3 Ways to Bind an Event to an
Element
67

 2️⃣Traditional DOM Event Handlers (Better


Approach)
 Uses JavaScript to bind events via
properties like onclick.
 Separates JavaScript from HTML, making
code cleaner.
 Can only attach one function per event.

CS380
3 Ways to Bind an Event to an
Element
68

 <p id="text">Hello, World!</p>


 <button id="btn">Click Me</button>
 <script>

document.getElementById("btn").on
click = function() {

document.getElementById("text").innerH
TML = "Welcome ISE";
CS380 };

3 Ways to Bind an Event to an
Element
69

 3️⃣DOM Level 2 Event Listeners (Modern


Approach - Recommended)
 Introduced in DOM Level 2 (Year 2000).
 Allows multiple functions to be attached
to the same event.
 Provides better compatibility when using
multiple scripts.

CS380
3 Ways to Bind an Event to an
Element
70

 <p id="text">Hello, World!</p>


 <button id="btn">Click Me</button>
 <script>

document.getElementById("btn").addEventListener("click
", function() {
 document.getElementById("text").innerHTML =
"Welcome ISE";
 });

 // Adding another function to the same event


document.getElementById("btn").addEventListener("click
CS380
", function() {
Event Listeners
71

 Event Listeners are functions in JavaScript that


wait for a specific event to occur on a particular
HTML element and then execute a specified
function.
 KeyPoints
 Modern Way of Handling Events:
 Introduced in DOM Level 2 (2000).
 Preferred over traditional event handlers (onclick,
onmouseover, etc.).
 Attach Multiple Functions to the Same Event:
 Unlike traditional handlers, it allows multiple functions
to respond to a single event.
CS380
Event Listeners
72

 element.addEventListener(event, function,
EventFlow);
 event: Type of event to listen for (e.g.,
"click", "mouseover").
 function: The code to run when the
event occurs.
 EventFlow (optional): Boolean
indicating if event capturing is used.
Defaults to false (bubbling).

CS380
Event Listeners
73
 <html>
 <body>
 <p id="text">Hello, World!</p>
 <button id="btn">Click Me</button>
 <script>
 let btn = document.getElementById("btn");
 let text = document.getElementById("text");
 // Adding first event listener to change text
 btn.addEventListener("click", function() { text.innerHTML =
"Welcome ISE"; });
 // Adding second event listener to show an alert
 btn.addEventListener("click", function() { alert("Button
Clicked!"); });
CS380 </script>

 </body>
Using Parameters with Event
74
Listeners
 Using Parameters with Event Listeners
 Event listeners can pass parameters to
functions by using an anonymous
function or arrow function.
 Directly calling a function with
parameters in addEventListener()
doesn't work, so a wrapper function is
needed.

CS380
✅ Example: Passing Parameters
75
 <html>
 <body>
 <p id="text">Hello, World!</p>
 <button id="btn">Click Me</button>
 <script>
 function changeText(message) {
 document.getElementById("text").innerHTML = message;
 }
 document.getElementById("btn").addEventListener("click",
function() {
 changeText("Welcome ISE");
 });
 </script>
 </body>
 </html>
CS380
Direct Function Call Doesn't
76
Work:
 btn.addEventListener("click",
changeText("Welcome ISE")); // ❌ Doesn't
work
 Use a Wrapper Function:
 Wrap the function call inside an anonymous
or arrow function to pass arguments.
 Preferred for Dynamic Data:
 Useful when the event listener needs to
work with dynamic data or multiple
parameters.
CS380
Event Object
77

 An Event Object in JavaScript is an


object that gets automatically passed to
event handler functions when an event
is triggered. It contains information
about the event, such as:
 The type of event (e.g., click, keydown,
mouseover).
 The element that triggered the event.
 Mouse position, key pressed, etc.,
depending on the type of event.
CS380
 <!DOCTYPE html>
 <html>
 <body>
78

 <button id="myButton">Click Me</button>


 <script>
 // Adding an event listener with an event object
 document.getElementById("myButton").addEventListener("click",
function(event) {
 console.log("Event Type: " + event.type); // Output: click
 console.log("Target Element: " + event.target.id); // Output:
myButton
 console.log("Mouse X Position: " + event.clientX); // X coordinate
of the mouse click
 console.log("Mouse Y Position: " + event.clientY); // Y coordinate
of the mouse click
 });
 </script>
CS380
 </body>
 <!DOCTYPE html>
 <html>
 <body>
79
 <button id="myButton">Click Me</button>
 <script>
 // Adding an event listener with an event object
 document.getElementById("myButton").addEventListener("click",
function(event) {
 console.log("=== All Properties of Event Object ===");
 // Looping through all properties of the event object
 for (let prop in event) {
 console.log(prop + ": " + event[prop]);
 }
 });
 </script>
 </body>
 </html>

CS380
Event---- actions
80

 Event listener- used to catch the event


on the html element.
 All Event listener will start with the name
“on_ _ _”
 E.g. onClick()
 Event handler- it is a fuction of JS
function call.

CS380
Bind an Event to an Element
81

 <a onclick="hide()">Click Me</a>


 <script>
 function hide() {
 alert("Link Clicked!");
 }
 </script>
 Event listener??
 Event handler??

CS380
✅ Event Bubbling
82

 Event Bubbling is the process where an


event triggered on a child element
bubbles up through its parent elements
until it reaches the root element.

 Example Scenario:
 If you click a button inside a <div>, the

click event will first trigger on the button


and then bubble up to the parent <div>
and beyond.

CS380
✅ Explanation:
83

 When you click the button (child), two


alerts will show up:
 Button Clicked! (Triggered by the button

itself)
 Div Clicked! (Event Bubbling) (Triggered

by the parent <div>)


 Why?

 The event bubbles up from the button to

the div.
 JavaScript executes the click event
CS380
 <!DOCTYPE html>
 <html>
 <body>

84
 <div id="parent" style="padding: 20px; background-color: lightblue;">
 <button id="child">Click Me</button>
 </div>
 <script>
 // Event listener for the child (button)
 document.getElementById("child").addEventListener("click", function() {
 alert("Button Clicked!");
 });

 // Event listener for the parent (div)


 document.getElementById("parent").addEventListener("click", function()
{
 alert("Div Clicked! (Event Bubbling)");
 });
 </script>
 CS380
</body>

📌 Preventing Event
85
Bubbling:
 To stop the bubbling, use:

 document.getElementById("child").addEventL
istener("click", function(event) {
 event.stopPropagation();
 alert("Button Clicked!");
 });
 Now, only "Button Clicked!" will appear.

CS380
Event bubbling and
86
caputring

CS380
✅ Event Capturing (Trickling
87
Phase)
 Event Capturing (also called trickling) is
the opposite of Event Bubbling.
 The event starts from the outermost
element (parent) and moves inward to
the target element (child).

CS380
 <!DOCTYPE html>
 <html>
 <body>
88
 <div id="parent" style="padding: 20px; background-color:
lightblue;">
 <button id="child">Click Me</button>
 </div>
 <script>
 // Parent element listener (Capturing Phase)
 document.getElementById("parent").addEventListener("click",
function() {
 alert("Div Clicked! (Event Capturing)");
 }, true); // 'true' enables capturing
 document.getElementById("child").addEventListener("click",
function() {
 alert("Button Clicked!");
 });
 </script>
CS380
 </body>

✅ Event Delegation
89

 Event Delegation is a technique where


you add a single event listener to a
parent element to handle events
triggered by its child elements.
 Instead of adding listeners to each child,
the parent’s listener captures events
bubbling up from children.
 📌 Why Use Event Delegation?
 Performance Improvement: Fewer event
listeners attached.
 Dynamic Elements Handling: Works even if
CS380
Without event delegation
90

 <button>Button 1</button>
 <button>Button 2</button>
 <button>Button 3</button>

 <script>
 let buttons = document.querySelectorAll("button");
 for (let i = 0; i < buttons.length; i++) {
 buttons[i].addEventListener("click", function() {
 alert("Button Clicked!");
 });
 }
 </script>
CS380
 <html>
 <body>

91

 <div id="bookshelf">
 <div class="book">Book 1</div>
 <div class="book">Book 2</div>
 <div class="book">Book 3</div>
 </div>
 <script>
 // Adding a single event listener to the bookshelf (parent)

document.getElementById("bookshelf").addEventListener("click",
function(event) {
 if (event.target.classList.contains("book")) {
 alert("You picked up: " + event.target.textContent);
 CS380 }
USER INTERFACE EVENTS
92

 📌 Explanation
 load Event - Alerts when the page fully
loads.
 unload Event - Logs a message when
the user leaves the page.
 scroll Event - Logs messages while
scrolling the page.
 resize Event - Logs a message when
resizing the browser window.
CS380
example
93

 <html>
 <body style="height: 2000px;">
 <h1>JavaScript Event Handling Example</h1>
 <script>
 // 1. 'load' Event
 window.addEventListener('load', function() {
 alert('Page is fully loaded!'); // Triggered when the
page finishes loading
 });
 // 2. 'unload' Event
 window.addEventListener('unload', function() {
 console.log('You are leaving the page.'); //
Triggered when the user leaves the page
CS380
 });
94
 // 3. 'scroll' Event
 window.addEventListener('scroll', function() {
 console.log('You are scrolling the page.'); // Triggered when the user
scrolls the page
 });

 // 4. 'resize' Event
 window.addEventListener('resize', function() {
 console.log('Window size changed!'); // Triggered when the window
is resized
 });
 </script>
 </body>
 </html>
CS380
✅ Focus & Blur Events
95
Example
 <html>
 <body>
 <h1>Focus & Blur Events Example</h1>
 <input type="text" id="nameInput" placeholder="Enter your name">
 <script>
 const inputField = document.getElementById("nameInput");

 // Focus event - When the input field is focused (clicked)


 inputField.addEventListener("focus", function() {
 inputField.style.backgroundColor = "lightyellow";
 console.log("Input field is focused!");
 });

CS380
96

 // Blur event - When the input field loses focus (clicked


outside)
 inputField.addEventListener("blur", function() {
 inputField.style.backgroundColor = "";
 console.log("Input field lost focus!");
 });
 </script>
 </body>
 </html>

CS380
✅ Mouse Events
97

 click - Triggered when the user clicks on an element.


 dblclick - Triggered when the user double-clicks on an
element.
 mousedown - Triggered when the mouse button is pressed
down.
 mouseup - Triggered when the mouse button is released.
 mousemove - Triggered when the mouse is moved over
an element.
 mouseover - Triggered when the mouse pointer enters an
element.
 mouseout - Triggered when the mouse pointer leaves an
element.
 mouseenter - Triggered when the mouse enters an
element (No child element trigger).
CS380

✅ Keyboard Events
98

 keydown - Triggered when a key is


pressed down (fires continuously if held
down).
 keypress - Triggered when a key is
pressed and released (Deprecated; use
keydown or keyup instead).
 keyup - Triggered when a key is
released.

CS380
✅ Form Events
99

 submit - Triggered when a form is submitted


(usually with a submit button).
 reset - Triggered when a form is reset to its initial

state.
 focus - Triggered when an element (like an input)

gains focus.
 blur - Triggered when an element (like an input)

loses focus.
 change - Triggered when the value of an input,

select, or textarea changes.


 input - Triggered when the user modifies the

value of an input or textarea.


CS380
Form enhancement and
10
validation
0
 ✅ Form Validation in JavaScript

 Form validation ensures data correctness


before processing.
 Enhances user experience by providing
immediate feedback.

CS380
Types of Validation
10
1
 Client-side Validation: Handled using
JavaScript before sending data to the
server.
 Server-side Validation: Handled on

the server for additional security.


 Common Validation Techniques

 Required fields check (e.g., Name,

Email).
 Pattern matching using Regular

Expressions (e.g., Email validation).


CS380

Example
10
2
 document.getElementById("myForm").addEventListener("s
ubmit", function(event) {
 event.preventDefault(); // Prevent form submission

 const name = document.getElementById("name").value;


 const email = document.getElementById("email").value;

 let errorMessage = ""; // To collect error messages

 // Check if the name is empty


 if (name === "") {
 errorMessage += "Name is required.\n";

CS380 }
Example
10
3
 // Check if the email is valid
 if (email === "") {
 errorMessage += "Email is required.\n";
 } else if (!email.includes("@") || !email.includes(".")) {
 errorMessage += "Invalid email address.\n";
 }

 // Display error message if validation fails


 if (errorMessage !== "") {
 alert(errorMessage);
 } else {
 alert("Form submitted successfully!");
 }
CS380
 });
✅ HTML5 Form Validations
10
4
 Required Field
 Ensures a field is not left empty.
 <input type="text" name="username" required>

 Email Validation
 Checks for valid email format.
 <input type="email" name="email" required>

 Number Validation
 Allows only numbers within a specified range.
 <input type="number" name="age" min="1" max="100"
required>
 Pattern
CS380 Matching
✅ HTML5 Form Validations
10
5
 Ensures minimum character length.
 <input type="password" name="password" minlength="6"
required>

 URL Validation
 Validates proper URL format.
 <input type="url" name="website" required>

 Date Validation
 Allows only date input.
 <input type="date" name="dob" required>
 Range Slider
CS380
✅ HTML5 Form Validations
10
6
 Select a value from a specified range.
 <input type="range" name="volume" min="0" max="100"
required>

 Multiple File Upload


 Allows selecting multiple files of specific types.
 <input type="file" name="files" accept=".jpg, .png"
multiple>

 Color Picker
 Allows user to select a color.
 <input type="color" name="favcolor" required>
CS380

You might also like