Module 2 Fsd Notes1
Module 2 Fsd Notes1
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Chapter 5
DOM (Document Object Model) specifies how browsers should create a model of an HTML page and
how the javascript can access and update the contents of a web page while it is in the browser window.
As a browser loads a web page, it creates a model of that page. The model is called a DOM tree, and it is
stored in the browsers’ memory. It consists of four main types of nodes.
<!DOCTYPE html>
<html>
<head>
<title>DOM Tree</title>
</head>
<body>
<h1 id="main-heading">Hello</h1>
<p class="intro">Welcome to the DOM.</p>
</body>
</html>
Every element, attribute, and piece of text in the HTML is represented by its own DOM node.
DOM Tree
Each node is an object with methods and properties. Scripts access and update this DOM tree (not the
source HTML file). Any changes made to the DOM tree are reflected in the browser.
The DOM tree consists of different types of nodes, arranged in a hierarchical manner:
1. Document Node
o The root of the tree, representing the entire document (document object in JavaScript).
2. Element Nodes
3. Attribute Nodes
o These are associated with element nodes but do not appear as children.
4. Text Nodes
DOM Manipulation
The Document Object Model (DOM) represents web page elements as nodes. When working with
the DOM, you interact with these nodes to access, modify, and manage elements. DOM
manipulation involves changing the structure, style, or content of a webpage dynamically using
JavaScript.
Step 1:
Accessing Elements –
Step 2:
There are several methods to access elements in the DOM. These can be grouped into:
Note:
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Note:
Once you have selected an element, you can navigate the DOM tree to find related elements.
Working with an HTML content.There are two key properties to manipulate content inside elements:
Property Description
innerHTML Returns or updates the HTML content inside an element (including child elements).
textContent Returns or updates only the text inside an element, ignoring any HTML tags.
The following methods allow you to dynamically create, add, or remove elements from the DOM:
Method Description
Attributes provide additional information about an element. You can get, update, or remove attributes
using the following properties and methods:
Selecting Elements
To manipulate elements, you first need to select them. JavaScript provides several methods for
selecting elements.
Methods:
• getElementById()
• getElementsByClassName()
• getElementsByTagName()
• querySelector()
• querySelectorAll()
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
• getElementById()
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
• getElementsByClassName()
• getElementsByTagName()
2. Creating and Adding Nodes - create element, create text node, append child
3. Modifying Nodes
4. Removing Nodes
1. Store the element to be removed in a variable,
2. store the parent of that element in a variable,
3. Remove the element from its containing element
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Attribute
Syntax
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
3. Removing attributes
3. Removing attributes
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Chapter 6 - Event
Keyboard Events
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Mouse Events
Example:
// Log a key press
document.addEventListener("keydown", function(event) {
console.log("Key pressed: " + event.key);
});
Instead of using inline event handlers, you should use JavaScript event listeners.
Separates JavaScript from HTML. It is supported in all major browsers. But can only attach one function
per event. Assigning another function will overwrite the previous one.
Syntax
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Traditional DOM Cleaner separation of JS and Only one event per element (overwrites
Handlers HTML existing handlers)
Always use addEventListener() for event handling unless supporting very old browsers.
Avoid inline HTML event handlers and traditional onevent handlers to keep your code clean and
maintainable.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Event Listeners
Event listeners are the modern and preferred way to handle events in JavaScript. They allow multiple
event handlers to be assigned to a single event on an element, unlike traditional event handlers, which only
support one function per event.
Syntax
i) The event you want it to listen for. In this case, the blur event.
ii) The code that you want itto run when the event fires.In this example, it is the checkUsername()
function.
(Note that the parentheses are omitted where the function is called because they would indicate that the
function should run as the page loads (rather than when the event fires)).
Because you cannot have parentheses after the function names in event handlers or listeners, passing
arguments requires a workaround.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
How function
Directly as checkUsername Inside an anonymous function
is passed?
How event (e) Automatically by JavaScript Manually inside the anonymous function
is passed?
Note:
Event listeners (addEventListener()) are the recommended way to handle events in JavaScript because:
1. They allow multiple functions to be attached to a single event.
2. They keep JavaScript separate from HTML, improving maintainability.
3. They provide better flexibility in event management.
Event Delegation
Event delegation is a technique in JavaScript where you attach an event listener to a parent (or ancestor)
element instead of adding separate event listeners to multiple child elements. This improves performance,
simplifies code, and ensures that dynamically added elements also receive event handling.
Creating event listeners for a lot of elements can slow down a page, but event flow allows you to listen for
an event on a parent element
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Forms in HTML allow websites to collect user information, such as login details, feedback, or payment
details. JavaScript helps improve this process by:
Validating input to ensure users provide correct and complete information before submission.
a) Form Enhancement
JavaScript improves user experience by adding interactive features like auto-complete, dynamic field
updates, and error highlighting.
Enhancements help users fill out forms more efficiently and reduce errors.
HTML5 introduced new form elements like <input type="email">, <input type="date">, and <datalist>.
c) Form Validation
JavaScript checks for missing or incorrect input and provides instant feedback.
Example: Checking if an email address is in the correct format before allowing submission.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
This section is about creating helper functions to handle events across different browsers, particularly
dealing with older versions of Internet Explorer (IE5-8). Let's break it down:
Instead of writing the same code multiple times, you write it once in a function and reuse it.
In this case, the helper function helps handle events in a way that works across all browsers.
Modern browsers use addEventListener(), while older Internet Explorer versions (IE5-8) use
attachEvent().
Instead of writing separate event-handling code for each browser, we create a single function that works
for all.
Note:
Stores the callback function as a property of the element (el['e' + event + callback]).
Form Element
The <form> element in HTML is special because it contains from controls(like
<input>,<select>,<textarea>, etc), and it has unique properties, methods, and events in the DOM.
1. Form properties
Forms have several properties that make them easy to access and manipulate.
Property Description
action The URL where the form data will be sent when submitted.
name Rarely used today. Instead, forms are usually selected by id.
A collection (like an array) of all form controls inside the form. Elements can be accessed by
elements
index number or name attribute.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Example:
Event Description
submit Fires when the form is submitted.
Reset Fires when the form is reset.
Property Description
Value Holds user input for text fields; otherwise, it reflects the value attribute.
Type Specifies the type of an <input> element (e.g., text, password, radio, checkbox).
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Property Description
defaultValue The initial value of a text box or text area when the page loads.
Form Refers to the <form> element that the input belongs to.
Boolean reflecting whether a checkbox or radio button was checked when the page
defaultChecked
loaded.
Method Description
Simulates a user clicking a button, checkbox, or file upload input. It also triggers a submit
click()
event when called on a submit button and a reset event on a reset button.
Event Description
Blur Triggered when the user moves away from an input field.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Event Description
keydown, keyup,
Triggered when a user interacts with the keyboard.
keypress
Submitting Forms
Explaining the Steps for Handling Form Submission Using JavaScript.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
The script is wrapped inside an IIFE to avoid polluting the global scope.
Select and store the password input field and checkbox elements using document.querySelector().
3. An event listener triggers an anonymous function when the show password checkbox is changed
4. The target of the event (the checkbox) is stored in a variable called target
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Older versions of Internet Explorer (IE) used event.srcElement, but modern browsers support
event.target.
5. A try...catch statement checks if an error occurs when changing the type attribute
Some browsers may not allow changing the type attribute dynamically.
Wrapping the code inside try...catch ensures errors are handled gracefully.
If the checkbox is checked, the password field becomes a text field, making the password visible.
9. If trying to change the type causes an error, the catch clause runs
If an error occurs when changing the type, the catch block handles it.
// Handle errors (for very old browsers that don't support changing input type)
alert("Sorry, your browser does not support changing password visibility.");
}
});
})();
Note:
Radio Button
1. Place the script in an IIFE (Immediately Invoked Function Expression)
The script is enclosed in an IIFE to avoid polluting the global scope.
This ensures the code runs automatically once the page loads.
2. Set up variables for form elements
The script starts by defining variables to hold:
The form
The collection of radio buttons
The "Other" radio button
The text input field (which will be shown or hidden)
3. Hide the text input initially
JavaScript updates the class attribute of the text input field to hide it.
This ensures the form still works for users without JavaScript.
4. Use a for loop to attach event listeners to radio buttons
The script loops through all radio buttons and adds an event listener to each.
When a radio button is clicked, the radioChanged() function is called.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Select Boxes
A <select> element in HTML is a dropdown menu that allows users to choose from multiple options. It
consists of multiple <option> elements representing the available choices.
Key Properties of <select>
1. options – Collection of all <option> elements inside the <select>.
2. selectedIndex – The index of the currently selected option (starts from 0).
3. length – The total number of options.
4. multiple – If set to true, users can select multiple options.
5. selectedOptions – Collection of all selected <option> elements.
Key Methods
1. add(option, before)
o Adds a new option to the list.
o The first parameter is the new <option>, and the second is the position where it should be
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
inserted.
2. remove(index)
o Removes an option from the list based on its index.
<label for="equipmentType">Type:</label>
<select id="equipmentType" name="equipmentType">
<option value="choose">Please choose a type</option>
<option value="cameras">Camera</option>
<option value="projectors">Projector</option>
</select>
<br>
<label for="model">Model:</label>
<select id="model" name="model">
<option>Please choose a type first</option>
</select>
<input id="submit" type="submit" value="Submit" />
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
3. Two objects are created; each one holds options used to populate the second select box (one has types
of cameras, the other has types of projectors).
4. When the user changes the first select box, an event listener triggers an anonymous function.
5. The anonymous function checks if the first select box has a value of choose.
6. If so, the second select box is updated with just one option, which tells the user to select a type.
7. No further processing is needed, and the return keyword exits the anonymous function (until the user
changes the first select box again).
8. If a type of equipment has been selected, the anonymous function continues to run, and a models
variable is created. It will store one of the objects defined in step 3 (cameras or projectors). This correct
object is retrieved using the getModels() function declared at the end of the script (9410), The function
takes one parameter this.value, which corresponds to the value from the option that was selected in first
select box.
9. Inside the getModels() function, an if statement checks if the value passed in was cameras; if so, it
returns the cameras object.
10. If not, it continues to run, checking to see if the value was projectors, and if so, it returns the projectors
object.
11. A variable called options is created. It will hold all the <option> elements for the second select box.
When this variable is created the first <option> is added to it; it tells users to choose a model.
12. A for loop goes through the contents of the object that was placed in the models variable in step (8-
10). Inside the loop, key refers to the individual items in the object.
13. Another <option> element is created for every item in the object. Its value attribute uses the property
name from the object. The content that sits between the <option> tags is that property's value.
14. The options are then added to the second select box using the innerHTML property.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
TextArea
When the cursor is in the textarea, a <span> element will be shown with a count of how many characters
the user has remaining. When the textarea loses focus, this message is hidden.
8. A variable called count holds the number of characters left to use (it does this by subtracting the number
of characters used from 140).
9.if... else statements are used to set the CSS class for the element that holds the message (these can also
show the message if it was hidden).
10. A variable called charMsg is created to store the message that will be shown to the user.
11. The message is added to the page
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
PlaceHolder Fallback
The HTMLS placeholder attribute lets you put words in text inputs (to replace labels or to add hints about
what to enter). When the input gains focus and the user starts typing, the text disappears. But
it only works in modern browsers, so this script ensures that the user sees placeholder text in older browsers
too. It is a basic example of a polyfill.
2. Check if the browser supports the HTML5 placeholder attribute, If it does, there is no need for the
fallback. Use return to exit the function.
3. Find out how many forms are on the page using the length property of the forms collection.
4. Loop through each <form> element on the page and call showP]aceholder() for each one, passing it the
collection of elements in that form.
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
7. An if statement checks each element to see if the element has a placeholder attribute with a value.
8. If there is no placeholder attribute, continue tells it to go on to the next element. Otherwise, it:
9. Changes the text color to gray, and sets the value of the element to be the placeholder text.
10. An event listener triggers an anonymous function when the element gains focus.
11. If the current value of the element matches the placeholder text, the value is cleared (and color
changed to black).
12. An event listener triggers an anonymous function when the element loses focus.
13. If the input is empty, the placeholder text is added back in (and its color changed to gray).
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
Form Validation
Validation checks if user input meets specific rules (e.g., a password must have at least 8 characters)
before submitting a form. we check user input when the form is submitted. Since users can submit a form
by pressing the "Submit" button or hitting Enter, validation is handled using the submit event, not the
button’s click event.
Types of Validation:
1. Client-Side Validation (Browser-Based) – Fast, done using HTML attributes or JavaScript.
• Example: <input type="email" required> ensures a valid email format.
2️. Server-Side Validation (Backend-Based) – More secure, prevents users from bypassing validation.
• Example: Django, PHP, or Node.js validating input before saving to a database.
Best Practice: Use both client-side and server-side validation for security and efficiency.
In order to check whether any errors were found, a variable called isFormValid is created and is given a
value of true. The script then loops through each property of the valid object, and if there was an error (if
any property of that object has a value of false), then there is an error in the form and the isFormValid
variable is also set to false.
So, isFormVal d is being used as a flag (you can think of it being like a master switch) if an error is found,
it is turned off. At the end of the script, if isFormValid is false then an error must have been found and the
form should not be submitted (using the preventDefault() method),
SJB Institute of Technology, Bangalore – 60
BACHELOR OF ENGINEERING
DEPARTMENT OF INFORMATION SCIENCE & ENGINEERING
It is important to check and process all of the elements before deciding whether to submit the form so that
you can show all of the relevant error messages in one go.
Custom Validation
The final part of the script performs three checks that apply to individual form elements; each check lives in
a named function.
Prepared By,
Prof. Ranjitha J,
Dept, of ISE
SJB Institute of Technology