0% found this document useful (0 votes)
34 views35 pages

Unit 1

Hello

Uploaded by

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

Unit 1

Hello

Uploaded by

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

Unit-1 Client-Side Scripting

 Client-side scripting refers to scripts that are executed on the user's browser
rather than on the server.
 JavaScript is the most commonly used client-side scripting language.
 It enables dynamic content updates, interactive features, and improved user
experience without requiring a page reload.
Need of Client-Side Scripting Language
 Interactivity:
Allows for dynamic content and user interaction without page reloads.
 Performance:
Reduces server load and latency by handling operations on the client side.
 Enhanced User Experience:
Provides immediate feedback and updates.
 Form Validation:
Validates user input before sending data to the server, reducing errors.
Java Script
 Java script is used to create client-side dynamic web pages.
 It was created by Brendan Eich while working for Netscape Communications
Corporation and was first released in 1995.
 Java script is an object-based scripting language which is lightweight and
cross platform.
 Java script is a translated language because its translator (embedded in the
browser) is responsible for translating the java script code to the web browser.
 Java script was designed to add interactivity to HTML pages.
 A java script is usually embedded direct in HTML pages.
 All major browsers like Netscape and internet explorer, support java script.
 Java script was developed for Netscape, Netscape 2 was the first browser to
run java script.
 After Netscape the Mozilla foundation continued to develop java script for the
Firefox browser.
 JavaScript is an essential tool for web developers because it enables dynamic
content, interactivity, and a better user experience on websites.
Advantages of java script
 Client-Side Execution
 Speed:
JavaScript is executed directly in the user's browser, which reduces the load
on the server and speeds up the user interface.
 Immediate Feedback:
Users get instant responses to their actions without the need for page reloads.
 Versatility and Flexibility
 Cross-Platform Compatibility:
JavaScript works on all major browsers and platforms, making it highly
versatile.
 Wide Range of Uses:
It can be used for both client-side (frontend) and server-side (backend)
development with frameworks like Node.js.
 Rich User Interfaces
 Interactivity:
JavaScript enables dynamic content updates, animations, and interactive
elements, enhancing user engagement.
 Rich Interfaces:
Libraries like jQuery and frameworks like React, Angular, and Vue.js allow
developers to create sophisticated and responsive user interfaces.
 Community
 Active Community:
A large, active community means abundant resources, tutorials, and support,
making it easier to learn and troubleshoot.
 Ease of Learning and Use
 Simple Syntax:
JavaScript’s syntax is relatively easy to learn, making it accessible for
beginners.
 Flexibility:
It allows both procedural and object-oriented programming styles, catering to
different development preferences.
 Real-Time Applications
 Real-Time Updates:
JavaScript is ideal for real-time applications like chat apps, online gaming,
and live updates due to its ability to handle asynchronous operations.
 Server-Side Development with Node.js
 Unified Development:
Using JavaScript for both client-side and server-side development streamlines
the development process and enhances consistency.
 Efficient Performance:
Node.js allows for high-performance server-side applications due to its non-
blocking, event-driven architecture.

Disadvantage of java script

 Client-Side Dependency:
 JavaScript runs on the client's browser, which can be a disadvantage if the
user's device has limited processing power or if JavaScript is disabled.
 Dependency on the Internet:
 Many JavaScript frameworks and libraries are hosted on CDNs (Content
Delivery Networks). If these resources are not available (e.g., due to network
issues), the functionality of the web application can be affected.
 Cannot create database application:
 By using java script, you cannot create the web site to the database. For this
you need to use server-side scripting.
 Browser compatibility issues:
 Not all browsers support the java script codes. The browser may support java
script as a whole, but may not support the codes or lines of codes written in
java script and may interpret differently.

Application of java script

Java script is used to create interactive websites. It is mainly used for

 Dynamic drop-down menus


 Client-side validation
 Displaying pop-up windows and dialog boxes (like an alert dialog box,
confirm dialog box and prompt dialog box)
 Display date and time
 Java script can calculate, manipulate and validate data
 Java script can change HTML content, attribute values etc.

Comparison java script and java


Formatting and Coding Conventions

 JavaScript are crucial for writing clean, readable, and maintainable code.
These practices help developers understand and collaborate on codebases
more effectively.
 formatting of JavaScript code is essential for readability, maintainability
developers. Below are key formatting guidelines, along with an example that
illustrates these principles.
 Coding conventions are style guidelines for programming.
 Coding conventions can be documented rules for teams to following or just be
your individual coding practice. Such as
 Naming Conventions
 Variables and Functions:
Use camelCase for naming variables and functions. Start with a lowercase
letter and capitalize the first letter of each subsequent word.
 Constants:
Use UPPER_CASE with underscores for constant values that do not change.
let userName = "JohnDoe"; // Variable
function calculateTotal(price, quantity) { // Function
return price * quantity;
}
const MAX_USERS = 100; // Constant
 Indentation and Spacing
 Use consistent indentation, typically 2 or 4 spaces per level. Avoid using tabs.
 Add spaces around operators (=, +, -, etc.) and after commas to improve
readability.

let a = 5;

let b = 10;

let sum = a + b;

 Semicolons
 Use semicolons to terminate statements.
let greeting = "Hello, World!";
console.log(greeting);
 Curly Braces and Blocks
 Place the opening curly brace { on the same line as the statement and the
closing brace } on a new line.
 Always use curly braces for blocks, even for single-line statements, to avoid
errors during maintenance.
if (isAuthenticated) {
console.log("User is authenticated");
} else {
console.log("User is not authenticated");
}
 Commenting
 Use single-line comments (//) for short explanations and multi-line comments
(/* ... */) for detailed descriptions. Comment on complex logic and important
sections to clarify the code's purpose.
// Calculate the area of a circle
function calculateArea(radius) {
/*
The formula for the area of a circle is:
area = π * radius^2
*/
return Math.PI * radius * radius;
}
 Consistent Function Expressions
 Use arrow functions (=>) for anonymous functions and callbacks when
appropriate, especially for simple functions.

let numbers = [1, 2, 3, 4, 5];


let squares = numbers.map(number => number * number);
console.log(squares);
 Avoid Global Variables
 Minimize the use of global variables to prevent namespace pollution. Use let
and const for block-scoped variables and constants, respectively.
function incrementCounter() {
let count = 0; // Local variable
count++;
return count;
}
 Use of Strict Mode
 Enable strict mode to catch common errors and improve performance by using
"use strict"; at the top of your scripts or functions.

"use strict";

function myFunction() {

let x = 10;

// Code here

Java Script Files

 JavaScript can be included in HTML in two ways:

 inline within <script> tags


 an external file. External files are preferred for better organization and
maintainability.

Example

<script src="main.js"></script>

Embedding java script in HTML

 JavaScript can be embedded direct within HTML using the <script> tag.
 It's a common practice to place script tags at the end of the <body> tag to
ensure that the DOM is fully loaded before the script runs.

<script>

document.write("This is embedded JavaScript.");


</script>

 The <script> tag is used to include JavaScript in an HTML document.


 The src attribute can be used to link to an external JavaScript file.

NoScript Tag

 The <noscript> tag defines alternative content for users who have disabled
JavaScript in their browsers.
 It ensures that important information is still accessible.
 The <noscript> element can be used in both <head> and <body>.
 When used inside the <head> element: <noscript> must contain only <link>,
<style>, and <meta> elements.

<noscript>

<p>JavaScript is disabled in your browser.</p>

</noscript>

Operators

 JavaScript supports various operators, including arithmetic, comparison,


logical, and assignment operators.

let x = 5;

let y = 10;

let sum = x + y; // Arithmetic

let isEqual = x == y; // Comparison

let isBothTrue = (x > 0) && (y > 0); // Logical

Control Structures

 Control structures like if, for, while, and switch are used to control the flow of
execution in JavaScript.
 They allow developers to make decisions, execute code conditionally, and
repeat tasks efficiently.
 The primary control structures in JavaScript include conditional statements,
loops, and branching statements.
 Conditional statements execute code based on specific conditions.

let age = 18;

if (age >= 18) {

console.log("You are an adult.");

} else {

console.log("You are a minor.");

1. If statement

 The if statement executes a block of code if a specified condition is true.


 Syntax

if (condition) {

// Code to execute if condition is true

 Example

let age = 18;

if (age >= 18) {

console.log("You are an adult.");

}
2. if...else Statement

 The if...else statement executes one block of code if the condition is true, and
another block if the condition is false.
 Syntax

if (condition) {

// Code to execute if condition is true

} else {

// Code to execute if condition is false

 Example

if (condition) {

// Code to execute if condition is true

} else {

// Code to execute if condition is false

3. if...else if...else Statement

 The if...else if...else statement allows for multiple conditions to be checked in


sequence. If one condition is true, the corresponding block of code is
executed, and the rest are skipped.
 Syntax

if (condition1) {

// Code to execute if condition1 is true

} else if (condition2) {
// Code to execute if condition2 is true

} else {

// Code to execute if both condition1 and condition2 are false

 Example

let score = 85;

if (score >= 90) {

console.log("Grade: A");

} else if (score >= 80) {

console.log("Grade: B");

} else if (score >= 70) {

console.log("Grade: C");

} else {

console.log("Grade: F");

4. switch Statement

 The switch statement executes one block of code among many options, based
on the value of an expression.

 It uses case labels to define possible values and default for the fallback
option.

 Syntax

switch (expression) {
case value1:

// Code to execute if expression === value1

break;

case value2:

// Code to execute if expression === value2

break;

// More cases...

default:

// Code to execute if no case matches

 Example

let day = 3;

switch (day) {

case 1:

console.log("Monday");

break;

case 2:

console.log("Tuesday");

break;

case 3:

console.log("Wednesday");
break;

case 4:

console.log("Thursday");

break;

case 5:

console.log("Friday");

break;

default:

console.log("Weekend");

Loops

 Loops execute a block of code repeatedly, based on a condition.


 They are useful for tasks that require repetition, such as iterating over arrays.

1. for loop

 The for loop is commonly used to execute a block of code a specific number
of times.
 It consists of three parts: initialization, condition, and increment/decrement.
 Syntax

for (initialization; condition; increment/decrement) {

// Code to execute repeatedly

 Example
for (let i = 0; i < 5; i++) {

console.log("Iteration " + i);

2. While loop

 The while loop executes a block of code as long as the specified condition is
true.
 It is useful when the number of iterations is not known in advance.
 Syntax
while (condition) {
// Code to execute repeatedly

 Example

let count = 0;

while (count < 3) {

console.log("Count is " + count);

count++;

3. do...while Loop

 The do...while loop is similar to the while loop, but it ensures that the code
block is executed at least once, even if the condition is false from the
beginning.
 Syntax

do {
// Code to execute repeatedly

} while (condition);

 Example

let n = 0;

do {

console.log("n is " + n);

n++;

} while (n < 3);

4. for…in loop

 The for...in loop iterates over the properties of an object.


 It is useful for traversing the properties of an object.
 Syntax

for (variable in object) {

// Code to execute for each property

 Example

let person = {firstName: "John", lastName: "Doe", age: 25};

for (let key in person) {

console.log(key + ": " + person[key]);

5. for…of loop
 The for...of loop iterates over iterable objects like arrays, strings, maps, etc. It
provides a simpler and more readable syntax for iterating over elements.
 Syntax

for (variable of iterable) {

// Code to execute for each element

 Example

let numbers = [10, 20, 30];

for (let number of numbers) {

console.log(number);

Array and For Each Loop

 An array in JavaScript is a collection of elements stored in a single variable.


 These elements can be of any data type, including numbers, strings, objects,
and even other arrays.
 Arrays are zero-indexed, meaning the first element has an index of 0, the
second element has an index of 1, and so on.
 create arrays using the array literal notation [] or the Array constructor.
 Example

// Using array literal

let fruits = ["Apple", "Banana", "Cherry"];


// Using Array constructor

let numbers = new Array(1, 2, 3, 4, 5);

Accessing Array Elements

 Array elements can be accessed using their index, which is the position of the
element in the array.
 Example

let colors = ["Red", "Green", "Blue"];

console.log(colors[0]); // Outputs: Red

console.log(colors[2]); // Outputs: Blue

Modifying Array Elements

 You can modify an array element by accessing it via its index and assigning a
new value.
 Example

let animals = ["Dog", "Cat", "Elephant"];

animals[1] = "Lion"; // Modifies the second element

console.log(animals); // Outputs: ["Dog", "Lion", "Elephant"]

Array Properties and Methods

 ‘length’ Property: Returns the number of elements in an array.

let numbers = [1, 2, 3, 4];

console.log(numbers.length); // Outputs: 4

 ‘push()’: Adds one or more elements to the end of an array and returns the
new length

let cities = ["New York", "Los Angeles"];


cities.push("Chicago");

console.log(cities); // Outputs: ["New York", "Los Angeles", "Chicago"]

 ‘pop()’: Removes the last element from an array and returns that element.

let colors = ["Red", "Green", "Blue"];

let lastColor = colors.pop();

console.log(colors); // Outputs: ["Red", "Green"]

console.log(lastColor); // Outputs: Blue

 ‘shift()’: Removes the first element from an array and returns that element.

let numbers = [1, 2, 3];

let firstNumber = numbers.shift();

console.log(numbers); // Outputs: [2, 3]

console.log(firstNumber); // Outputs: 1

 ‘unshift()’: Adds one or more elements to the beginning of an array and


returns the new length.

let animals = ["Cat", "Dog"];

animals.unshift("Elephant");

console.log(animals); // Outputs: ["Elephant", "Cat", "Dog"]

 ‘splice()’: Adds or removes elements from an array.

let fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.splice(2, 0, "Lemon", "Kiwi"); // Adds elements at index 2

console.log(fruits); // Outputs: ["Banana", "Orange", "Lemon", "Kiwi",


"Apple", "Mango"]
‘forEach’ Loop

 The ‘forEach’ loop in JavaScript is a method that executes a provided function


once for each array element.
 It is a simple way to iterate over an array compared to traditional loops like
‘for’ or ‘while’.
 The ‘forEach’ method takes a callback function as an argument, which is
called for each element in the array.
 Syntax

array.forEach(function(currentValue, index, array) {

// Code to execute for each element

});

 ‘currentValue’: The current element being processed in the array.


 ‘index’: (Optional) The index of the current element being processed
 ‘array’: (Optional) The array that forEach is being applied to

 Example

let numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(number) {

console.log(number * 2); // Outputs double of each element

});

Defining and Invoking Functions

 Function Definition: Declaring a function using the ‘function’ keyword. This


is known as a function declaration.
 Function Invocation: Calling a function by its name followed by parentheses
‘()’.
 Such as
function functionName(parameters) {
// Function body
// Code to be executed
}
 functionName: The name of the function.
 parameters: Optional. A comma-separated list of arguments that the function
expects.
 Function body: The code that will run when the function is called.
 Example
function greet(name) {
console.log("Hello, " + name + "!");
}

// Example of invoking the function


greet("Alice"); // Outputs: Hello, Alice!

Function Expression

 A function can also be defined as an expression. This is known as a function


expression.

const functionName = function(parameters) {

// Function body

// Code to be executed

};

Example

const add = function(a, b) {

return a + b;

};

// Example of invoking the function


const sum = add(2, 3); // sum will be 5

console.log(sum); // Outputs: 5

In this example:

 add is a variable assigned to an anonymous function that takes two


parameters, a and b.
 The function returns the sum of a and b.
 The function is called with the arguments 2 and 3, and the result is stored in
the variable sum.
 The result, 5, is then logged to the console.

Allow functions

 Arrow functions provide a shorter syntax for writing functions.


 They are always anonymous and do not have their own this context.
const functionName = (parameters) => {
// Function body
// Code to be executed
};
 Example
const add = (a, b) => {
return a + b;
};

console.log(add(2, 3)); // Output: 5

Invoking Functions

 To execute a function, you call or invoke it using its name followed by


parentheses ‘()’.
functionName(arguments);
 functionName: The name of the function to invoke.
 arguments: A comma-separated list of values to pass to the function.
Example
greet("Alice"); // Invokes the greet function with "Alice" as an argument
const result = add(2, 3); // Invokes the add function and stores the result
Function Return Values

 Functions can return values using the ‘return’ statement.


 When a function reaches a ‘return’ statement, it stops execution and returns
the specified value to the caller.
 Example

// Function that returns a number

function add(a, b) {

return a + b;

// Function that returns a string

function greet(name) {

return "Hello, " + name + "!";

// Function that returns a boolean

function isEven(number) {

return number % 2 === 0;

}
// Calling the functions and logging the return values

console.log(add(5, 3)); // Output: 8

console.log(greet("Alice")); // Output: Hello, Alice!

console.log(isEven(4)); // Output: true

console.log(isEven(7)); // Output: false

Returning an Object

 A function can return an object, which can be used to return multiple values as
properties.
 Example

// Function that returns an object

function createPerson(name, age) {

return {

name: name,

age: age

};

// Calling the function and storing the return value in a variable

const person = createPerson("Bob", 25);

// Accessing the properties of the returned object


console.log(person.name); // Output: Bob

console.log(person.age); // Output: 25

Returning an Array

 A function can return an array, which can be useful for returning multiple
values in a list.
 Example

// Function that returns an array

function getScores() {

return [85, 92, 78, 99];

// Calling the function and storing the return value in a variable

const scores = getScores();

// Accessing the elements of the returned array

console.log(scores); // Output: [85, 92, 78, 99]

console.log(scores[0]); // Output: 85

console.log(scores[3]); // Output: 99

Returning a Function

 A function can return another function, which can then be called later.
 This is a common pattern in functional programming.
 Example

// Function that returns another function


function multiplyBy(factor) {

return function(number) {

return number * factor;

};

// Calling the outer function and storing the returned function

const double = multiplyBy(2);

const triple = multiplyBy(3);

// Calling the returned functions

console.log(double(5)); // Output: 10

console.log(triple(5)); // Output: 15

Returning Undefined

 If a function doesn't explicitly return a value, it returns undefined by default.


 Example

// Function without a return statement

function sayHello() {

console.log("Hello!");

}
// Calling the function

const result = sayHello(); // Output: Hello!

console.log(result); // Output: undefined

Default Parameters

 Default parameters can be specified for functions, providing default values if


no arguments are passed.
 Example

function greet(name = "Guest") {

console.log("Hello, " + name + "!");

greet(); // Logs "Hello, Guest!"

greet("Alice"); // Logs "Hello, Alice!"

Rest Parameters in JavaScript

 Rest parameters in JavaScript provide a way to represent an indefinite number


of arguments as an array. This feature allows functions to accept an arbitrary
number of arguments without explicitly listing each one.

Syntax and Usage

 The rest parameter syntax consists of three dots (...) followed by a parameter
name.
 It must be the last parameter in the function's parameter list, as it collects all
remaining arguments passed to the function.
 Syntax

function functionName(...restParameter) {

// Function body

 Example

function sum(...numbers) {

return numbers.reduce((acc, num) => acc + num, 0);

console.log(sum(1, 2, 3, 4)); // Output: 10

console.log(sum(5, 10, 15)); // Output: 30

In this example, the sum function uses rest parameters to collect all arguments
passed to it into an array called numbers. The function then uses the reduce method
to sum up all the numbers.

Date Objects

 The ‘Date’ object in JavaScript is used to work with dates and times.
 It provides various methods to manipulate and format date and time values.
 Such as

1. Creating Date Objects

 Date objects can be created using the ‘new Date()’ constructor.


 There are several ways to create a date object, depending on the type of date
and time value

 Current Date and Time

 To create a ‘Date’ object with the current date and time:


 Example

const now = new Date();

console.log(now); // Outputs the current date and time

 Specific Date and Time

 To create a Date object with a specific date and time, pass the year, month,
day, hour, minute, second, and millisecond (all optional) as arguments:
 Example

const specificDate = new Date(2023, 7, 4, 15, 30, 0, 0); // August 4, 2023,


15:30:00

console.log(specificDate);

 Note

Year: A four-digit number representing the year.


Month: A zero-indexed number (0 for January, 11 for December).
Day: The day of the month (1-31).
Hour: The hour of the day (0-23).
Minute: The minutes (0-59).
Second: The seconds (0-59).
Millisecond: The milliseconds (0-999).
 Date String
 You can also create a Date object by passing a date string.
 Example

const dateFromString = new Date("August 4, 2023 15:30:00");


console.log(dateFromString);
2. Date Methods

 The ‘Date’ object has a variety of methods for getting and setting date and
time values.
a. Getting Date and Time Components
 getFullYear(): Returns the four-digit year.
 getMonth(): Returns the month (0-11).
 getDate(): Returns the day of the month (1-31).
 getDay(): Returns the day of the week (0-6), where 0 represents Sunday.
 getHours(): Returns the hour (0-23).
 getMinutes(): Returns the minutes (0-59).
 getSeconds(): Returns the seconds (0-59).
 getMilliseconds(): Returns the milliseconds (0-999).
 getTime(): Returns the number of milliseconds since January 1, 1970.
 Example
const now = new Date();
console.log(now.getFullYear()); // Outputs: 2024
console.log(now.getMonth()); // Outputs: 7 (August)
console.log(now.getDate()); // Outputs: 4
console.log(now.getDay()); // Outputs: 0 (Sunday)
console.log(now.getHours()); // Outputs: 15 (3 PM)
console.log(now.getMinutes()); // Outputs: 30
console.log(now.getSeconds()); // Outputs: 0
console.log(now.getMilliseconds()); // Outputs: 0
console.log(now.getTime()); // Outputs the milliseconds since epoch

b. Setting Date and Time Components

 ‘setFullYear(year, [month], [day])’: Sets the year.


 ‘setMonth(month, [day])’: Sets the month (0-11).
 ‘setDate(day)’: Sets the day of the month (1-31).
 ‘setHours(hour, [minute], [second], [millisecond])’: Sets the hour.
 ‘setMinutes(minute, [second], [millisecond])’: Sets the minutes.
 ‘setSeconds(second, [millisecond])’: Sets the seconds.
 ‘setMilliseconds(milliseconds)’: Sets the milliseconds.
 ‘setTime(milliseconds)’: Sets the date and time based on milliseconds since
January 1, 1970.
Example
const myDate = new Date();
myDate.setFullYear(2025);
myDate.setMonth(11); // December
myDate.setDate(25);
console.log(myDate); // Outputs: Thu Dec 25 2025
c. Date Formatting
 ‘toDateString()’: Returns the date portion of the date as a string.
 ‘toTimeString()’: Returns the time portion of the date as a string.
 ‘toISOString()’: Returns the date as a string in ISO format (YYYY-MM-
DDTHH:mm.sssZ).
 ‘toLocaleDateString()’: Returns the date portion of the date as a string, using
locale-specific conventions.
 ‘toLocaleTimeString()’: Returns the time portion of the date as a string, using
locale-specific conventions.
 ‘toLocaleString()’: Returns the date and time as a string, using locale-specific
conventions.

Example

const now = new Date();

console.log(now.toDateString()); // Outputs: "Sun Aug 04 2024"

console.log(now.toTimeString()); // Outputs: "15:30:00 GMT+0000


(Coordinated Universal Time)"

console.log(now.toISOString()); // Outputs: "2024-08-04T15:30:00.000Z"

console.log(now.toLocaleDateString()); // Outputs: "8/4/2024" (format may


vary based on locale)
console.log(now.toLocaleTimeString()); // Outputs: "3:30:00 PM" (format
may vary based on locale)

console.log(now.toLocaleString()); // Outputs: "8/4/2024, 3:30:00 PM"


(format may vary based on locale)

Interacting With the Browser

 Interacting with the browser in JavaScript involves using the Web APIs
provided by the browser.
 These APIs allow you to manipulate the DOM (Document Object Model),
handle events, communicate with servers, store data, and more.
 Here's an overview of some common interactions.

 A document object represents the HTML document that displayed in that


window. The document object has various properties that refer to other objects
which allow access to and modification of document content.
 The way a document content is accessed and modified is called the Document
Object Model (DOM).
 The objects are organized in a hierarchy. This hierarchical structure applies to
the organization of objects in a web document.
 Windows object: Top of the hierarchy. It is the outmost element of the object
hierarchy.
 Document object: Each HTML document that gets loaded into a window
becomes a document object. The document contains the contents of the page.
 Form object: Everything enclosed in the <form>…</form> tags sets the form
object.
 Form control elements: The form object contains all the elements defined for
that object such as text fields, buttons, radio buttons, and check boxes.

Why DOM is required in java script

 Java script can change all the HTML elements and attribute in the page
 Java script can change all the CSS styles in the page
 Java script can remove existing HTML elements and attributes
 Java script can add new HTML events in the page
 Java script can react to all existing HTML events in the page
 Java script can create new HTML events in the page
1. DOM Manipulation
 The DOM represents the HTML structure of a webpage.
 JavaScript can be used to modify elements, create new ones, or remove them.
 Example: Changing the text of an element
<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation Example</title>
</head>
<body>
<p id="demo">Hello, World!</p>
<button onclick="changeText()">Click me</button>

<script>
function changeText() {
document.getElementById("demo").innerHTML = "You clicked the
button!";
}
</script>
</body>
</html>
2. Local Storage
 You can store data locally in the browser using ‘localStorage’ or
‘sessionStorage’.
 Example: Using localStorage
<!DOCTYPE html>
<html>
<head>
<title>Local Storage Example</title>
</head>
<body>
<input type="text" id="name" placeholder="Enter your name">
<button onclick="saveName()">Save Name</button>
<p id="greeting"></p>

<script>
function saveName() {
var name = document.getElementById("name").value;
localStorage.setItem("name", name);
document.getElementById("greeting").innerHTML = "Hello, " + name;
}

window.onload = function() {
var name = localStorage.getItem("name");
if (name) {
document.getElementById("greeting").innerHTML = "Hello, " + name;
}
}
</script>
</body>
</html>
3. Window Object
 The ‘window’ object represents the browser window.
 It has methods for opening new windows, navigating, and controlling the
window.
 Example: Opening a new window
<!DOCTYPE html>
<html>
<head>
<title>Window Object Example</title>
</head>
<body>
<button onclick="openWindow()">Open youtube</button>

<script>
function openWindow() {
window.open("https://www.youtube.com", "_blank",
"width=500,height=500");
}
</script>
</body>
</html>

4. Event Handling
 JavaScript allows you to handle events like clicks, form submissions,
keypresses, etc.
 Example: Handling a button click
<!DOCTYPE html>
<html>
<head>
<title>Event Handling Example</title>
</head>
<body>
<button id="myButton">Click me</button>

<script>
document.getElementById("myButton").addEventListener("click",
function() {
alert("Button was clicked!");
});
</script>
</body>
</html>
5. Fetching Data (AJAX)
 You can use the fetch API to make HTTP requests to servers and get data
without reloading the page.
 Example: Fetching data from an API
<!DOCTYPE html>
<html>
<head>
<title>Fetch API Example</title>
</head>
<body>
<button id="fetchData">Fetch Data</button>
<div id="output"></div>

<script>
document.getElementById("fetchData").addEventListener("click",
function() {
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then(response => response.json())
.then(data => {
document.getElementById("output").innerHTML =
JSON.stringify(data);
})
.catch(error => console.error('Error:', error));
});
</script>
</body>
</html>
6. Navigator Object
 The ‘navigator’ object contains information about the browser and the user's
device.
 Example: Getting browser information
<!DOCTYPE html>
<html>
<head>
<title>Navigator Object Example</title>
</head>
<body>
<button onclick="getBrowserInfo()">Get Browser Info</button>
<p id="browserInfo"></p>

<script>
function getBrowserInfo() {
var info = "Browser: " + navigator.appName + "<br>" +
"Version: " + navigator.appVersion + "<br>" +
"Platform: " + navigator.platform + "<br>" +
"User Agent: " + navigator.userAgent;
document.getElementById("browserInfo").innerHTML = info;
}
</script>
</body>
</html>

You might also like