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

JS Advanced

java script advanced

Uploaded by

anjanashri108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

JS Advanced

java script advanced

Uploaded by

anjanashri108
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

JAVASCRIPT

1. Document Object Model


2. Two Dimensional Array
3. Callback Functions
4. Form Handling: Get/Post Method
5. Form Validation
6. Password Validation
7. Number Validation
8. HTML Events
9. PredefinedEvents
10. Event Driven Programming
11. Events
12. Actions
13. Listeners
14. Keyboard and Mouse Event
DOM
The Document Object Model (DOM) is like a virtual representation of a web
page. Imagine the web page as a digital document, structured like a tree with
branches and leaves. Each element on the web page, such as headings,
paragraphs, images, and buttons, is like a branch or leaf on this tree. The DOM
provides a structured way for JavaScript to interact with this "document tree."

Every element, attribute, and piece of text within the web page is a node in the
DOM tree. For instance, a <p> within a <div> is considered a child of that div
element.

Using the DOM, we can dynamically change the content, style, or structure of
the web page. It can access individual nodes, modify their attributes, update their
text content, or even add or remove elements from the page. Additionally,
JavaScript can set up event listeners on nodes such as clicks or keyboard inputs
creating interactive and responsive web experiences.

Overall It allows developers to create engaging user interfaces, validate user input,
update content dynamically, and respond to user interactions in real-time.

DOM Tree

The DOM tree is a hierarchical representation of a HTML document, with each


element, attribute, and text being represented as a node in the tree. These
elements can have parent-child relationships, creating a nested structure within
the document. Text content within elements is represented as text nodes, while
attributes of elements are represented as attribute nodes. Understanding the
DOM tree is crucial for web developers as it allows them to access, manipulate,
and dynamically update the content and structure of web pages using

Node relationships
1. Parent Nodes:
● A parent node is an element that contains other elements or nodes inside it.
● For example, in <div> <p>Hello</p> </div>, the <div> element is the parent
node of the <p> element.
● Each element can have only one parent node.

2. Child Nodes:
● Child nodes are elements or nodes that are directly inside another element,
known as the parent node.
● For instance, in <div> <p>Hello</p> </div>, the <p> element is the child node
of the <div> element.
● An element can have multiple child nodes.

3. Sibling Nodes:
● Sibling nodes are elements that share the same parent node.
● For example, in <div> <p>Hello</p> <span>World</span> </div>, the <p> and
<span> elements are sibling nodes.
● Sibling nodes are at the same level in the DOM tree and have the same
parent.
4. Ancestor Nodes:
● An ancestor node is any parent node, grandparent node, or any node higher up
in the hierarchy from a given node.
● For example, in <div> <p> <span>Hello</span> </p> </div>, the <div> element
is an ancestor/grandparent node of the <span> element.

5. Descendant Nodes:
● A descendant node is any child node, grandchild node, or any node lower down
in the hierarchy from a given node.
● For instance, in <div> <p> <span>Hello</span> </p> </div>, the <span>
element is a descendant/grandchild node of the <div> element.

Finding HTML Elements


● getElementById(): This method recovers an element by its unique ID attribute.
IDs must be unique within the HTML document.
let element = document.getElementById("elementId");

● getElementsByClassName(): This method returns a collection of elements that


have a specified class name.
let elements =
document.getElementsByClassName("className");

● getElementsByTagName(): This method recovers a collection of elements with a


specified tag name.
let elements =
document.getElementsByTagName("tagName");
● querySelector(): This method returns the first element within the document that
matches a specified CSS selector.
let element = document.querySelector("selector");

● querySelectorAll(): Similar to querySelector(), but returns a NodeList containing


all matching elements within the document.
let elements = document.querySelectorAll("selector");

Changing HTML Output stream


● Changing Text Content: can directly modify the text content of HTML elements.
This can be done by using properties like innerText or textContent or innerHTML.
// Changing text content using innerText
document.getElementById("elementId").innerText = "New
text";

// Changing text content using innerHTML


document.getElementById("elementId").innerHTML =
"<p>New paragraph</p>";

● Modifying Attributes: JavaScript can also modify attributes of HTML elements.


This includes attributes like src, href, class, id, etc.
// Modifying attribute
document.getElementById("imageId").src =
"newImage.jpg";

● Adding or Removing Elements: JavaScript can dynamically add or remove


elements from the DOM tree.
// Adding a new paragraph element
let newParagraph = document.createElement("p");
newParagraph.innerText = "New paragraph content";
document.getElementById("parentElement").appendChild(ne
wParagraph);

// Removing an existing element


let elementToRemove =
document.getElementById("elementToRemove");
elementToRemove.parentNode.removeChild(elementToRemove)
;

● Changing Styling: JavaScript can change the styling (CSS) of HTML elements by
modifying their style properties.
// Changing CSS style
document.getElementById("elementId").style.color =
"red";

Reacting to events
Events are actions detected by the browser. For example, clicking a button or
submitting a form.

HTML Event attributes


Attributes that define specific actions to be taken when certain events occur. For
instance, onclick specifies an action to be performed when an element is clicked.
<button onclick="alert('Button clicked!')">Click
Me</button>

Assign Events Using the HTML DOM


Events can also be assigned by accessing elements from the DOM and attaching
event listeners.
● The onload and onunload Events: These events occur when a page is loaded or
unloaded, respectively.
<script>
window.onload = function() {
alert('Page loaded!');
};
window.onunload = function() {
alert('Page unloaded!');
};
</script>

● The onchange Event: This event is triggered when the value of an input element
changes
<input type="text" id="myInput">
<script>
document.getElementById("myInput").onchange =
function() {
alert('Input value changed!');
};
</script>

● The onmouseover and onmouseout Events: These events occur when the mouse
pointer moves over or away from an element, respectively.
<button id="myButton" onmouseover="alert('Mouse
over!')" onmouseout="alert('Mouse out!')">Hover
Me</button>

● The onmousedown, onmouseup and onclick Events: These events occur when the
mouse button is pressed down, released, and clicked, respectively.
<button id="myButton" onmousedown="alert('Mouse
down!')" onmouseup="alert('Mouse up!')"
onclick="alert('Button clicked!')">Click Me</button>
Two dimensional array
Two-dimensional array is an array of arrays, where each element of the outer
array is itself an array
// Creating a 2D array (matrix) with 3 rows and 3 columns
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];

// Accessing elements of the 2D array


console.log(matrix[0][0]); // Output: 1
console.log(matrix[1][2]); // Output: 6

Callback functions
Callback functions are functions passed as arguments to other functions and
executed later when some operation is completed or an event occurs
// Higher-order function with a callback
function greet(name, callback) {
console.log("Hello, " + name + "!");
callback(); // Execute the callback function
}

// Callback function
function sayGoodbye() {
console.log("Goodbye!");
}

// Calling the higher-order function with the callback


greet("Alice", sayGoodbye);
//output:
Hello, Alice!
Goodbye!

Form Handling: Get/Post Method


Get method
GET method appends the data to the URL as query parameters, making it visible
in the address bar. It is suitable for transferring small amounts of data, such as
search queries, and is commonly used for simple data regaining operations.
However, it has limitations in terms of the amount of data it can handle and is
less secure for sensitive information since the data is visible in the URL

Post method
POST method sends data in the request body. This method is suitable for
transferring large amounts of data or sensitive information securely. It is
commonly used for submitting forms, uploading files, or performing actions that
modify server-side data. POST requests have no length restrictions, making them
ideal for transferring complex data structures.

Form Validation
Form validation is the process of ensuring that user input meets specific criteria
before submitting it to a server. There are two main types of form validation:
basic validation and data format validation.
Basic validation
Basic validation checks whether the required fields are filled in and whether the
input meets minimum length or maximum length requirements. Basic validation
ensures that all necessary information is provided.

<form id="myForm">
<input type="text" id="name" placeholder="Enter your
name" required>
<input type="email" id="email" placeholder="Enter your
email" required>
<button type="submit">Submit</button>
</form>

<script>

document.getElementById("myForm").addEventListener("submit
", function(event) {
let name =
document.getElementById("name").value.trim();
let email =
document.getElementById("email").value.trim();

if (!name || !email) {
alert("Please fill in all fields.");
event.preventDefault();
}
});
</script>
Data format validation
Data format validation checks whether the input data obeys to a specific format,
such as email addresses, phone numbers, or dates. Data format validation ensures
that the provided data is in the expected format

<form id="myForm">
<input type="text" id="email" placeholder="Enter your
email" required>
<button type="submit">Submit</button>
</form>

<script>

document.getElementById("myForm").addEventListener("submit
", function(event) {
let email =
document.getElementById("email").value.trim();
let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

if (!emailRegex.test(email)) {
alert("Please enter a valid email address.");
event.preventDefault();
}
});
</script>

Password Validation
Password validation typically checks if the password meets certain criteria, such
as minimum length, containing both letters and numbers, and special characters.
<form id="passwordForm">
<input type="password" id="password"
placeholder="Enter your password" required>
<button type="submit">Submit</button>
</form>

<script>

document.getElementById("passwordForm").addEventListener("
submit", function(event) {
let password =
document.getElementById("password").value.trim();
let passwordRegex =
/^(?=.*\d)(?=.*[a-zA-Z]).{6,}$/;

if (!passwordRegex.test(password)) {
alert("Password must contain at least 6
characters, including at least one letter and one
number.");
event.preventDefault();
}
});
</script>

Number validation
Number validation ensures that the input is a valid number, optionally with
decimal points.

<form id="numberForm">
<input type="text" id="number" placeholder="Enter a
number" required>
<button type="submit">Submit</button>
</form>
<script>

document.getElementById("numberForm").addEventListener("su
bmit", function(event) {
let number =
document.getElementById("number").value.trim();
let numberRegex = /^\d+$/;

if (!numberRegex.test(number)) {
alert("Please enter a valid number.");
event.preventDefault();
}
});
</script>

Html events
HTML events are actions or occurrences that happen in the browser environment.
Examples include clicks, submissions, mouse movements, keyboard inputs, etc.
These events can be triggered by user interactions (such as clicking a button) or
by the browser itself (such as page loading).

Predefined events
● Predefined events are common actions recognized by browsers. They include
events like clicks (click), submissions (submit), mouse movements (mouseover,
mouseout), keyboard inputs (keydown, keyup), etc.

Event driven programming


● Programming paradigm where the flow of the program is determined by events
occurring in the system rather than by the code sequentially.
● In event-driven programming, the program responds to events triggered by user
interactions or other parts of the system.

Events, Actions, Listeners:


● Events are specific occurrences or actions that happen in the browser
environment, such as clicks, submissions, or key presses.
● Actions are the responses or behaviours that occur in response to events. These
actions can include modifying the DOM, updating data, or triggering other
functions.
● Event listeners are functions that "listen" for specific events to occur and then
execute predefined actions in response.

Keyboard and Mouse Events:


● Keyboard events occur when a user interacts with the keyboard, such as
pressing keys or releasing keys. Examples include keydown, keyup, and
keypress.
● Mouse events occur when a user interacts with the mouse, such as moving
the mouse pointer or clicking mouse buttons. Examples include click,
mouseover, mouseout, mousedown, and mouseup.
<button id="myButton">Click Me</button>

<script>
// Event listener for button click event

document.getElementById("myButton").addEventListener("clic
k", function() {
alert("Button clicked!");
});
// Event listener for keyboard key press event
document.addEventListener("keydown",
function(event) {
if (event.key === "Enter") {
alert("Enter key pressed!");
}
});

// Event listener for mouse hover event


document.addEventListener("mouseover", function()
{
console.log("Mouse hovered over the
document!");
});

// Event listener for mouse click event


document.addEventListener("click", function() {
console.log("Mouse clicked anywhere on the
document!");
});
</script>

You might also like