0% found this document useful (0 votes)
3 views64 pages

Unit Iv Web Design

Easy iot file

Uploaded by

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

Unit Iv Web Design

Easy iot file

Uploaded by

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

APOLLO ARTS AND SCIENCE COLLEGE CHENNAI

UNIT IV WEB DESIGN AND DEVELOPMENT

UNIT IV:

JavaScript : Client side scripting, What is JavaScript, How to develop


JavaScript, simple JavaScript, variables, functions, conditions, loops and repetition,
Advance script, JavaScript and objects, JavaScript own objects, the DOM and web
browser environments, forms and validations

CLIENT SIDE SCRIPTING

▪ Client side scripting is a process in which the code along with HTML
web page is sent to the client by the server.
▪ Here, the code refers to the script. client side scripting is a process in
which scripts are executed by browsers without connecting the server.
▪ The code executes on the browser of client’s computer either during the
loading of web page or after the web page has been loaded.
▪ Client side scripting is mainly used for dynamic user interface elements,
such as pull-down menus, navigation tools, animation buttons, data
validation purpose, etc.
▪ JavaScript and jQuery are by far the most important client-
side scripting languages or web scripting languages and widely used
to create a dynamic and responsive webpage and websites.
▪ The browser (temporarily) downloads the code in the local computer
and starts processing it without the server. Therefore, the client side
scripting is browser dependent.
▪ A client-side script is a small program (or set of instructions) that is
embedded (or inserted) into a web page. It is processed within the client
browser instead of the web server.

1
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

▪ The client side script downloads at the client end from the server along
with the HTML web page it is embedded in. The web browser interprets
and executes the code and then displays the results on the monitor.
▪ The script that executes on the user’s computer system is called client.
It is embedded (or inserted) within the HTML document or can be
stored in an external separate file (known as external script).
▪ The script files are sent to the client machine from the web server (or
severs) when they are requested. The client’s web browser executes the
script, then displays the web page, including any visible output from
the script.

2
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Popular Client side Scripting Language

A language in which a client side script or program is written using syntax is


called client side scripting language or client side programming.
The most popular client side scripting languages is as follows:

SERVER-SIDESCRIPTING :

▪ Web servers are used to execute server-side scripting. They are


basically used to create dynamic pages.

▪ It can also access the file system residing at the webserver. A server-
side environment that runs on a scripting language is a web server.

▪ Scripts can be written in any of a number of server-side scripting


languages available. It is used to retrieve and generate content for
dynamic pages.
▪ It is used to require to download plugins. In this load times are
generally faster than client-side scripting. When you need to store and
retrieve information a database will be used to contain data.
▪ It can use huge resources of the server. It reduces client-side
computation overhead. The server sends pages to the request of the
user/client.
Difference between client-side scripting and server-side scripting :

Client-side scripting Server-side scripting

Source code is not visible to the user


because its output
Source code is visible to the user.
of server-sideside is an HTML page.

3
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Client-side scripting Server-side scripting

Its primary function is to manipulate and


Its main function is to provide the
provide access to the respective database as
requested output to the end user.
per the request.

In this any server-side technology can be


It usually depends on the browser used and it does not
and its version. depend on the client.

It runs on the user’s computer. It runs on the web server.

There are many advantages linked


The primary advantage is its ability to
with this like faster.
highly customize, response
response times, a more interactive
requirements, access rights based on user.
application.

It does not provide security for


It provides more security for data.
data.

It is a technique used in web It is a technique that uses scripts on the web


development in which scripts run server to produce a response that is
on the client’s browser. customized for each client’s request.

HTML, CSS, and javascript are


PHP, Python, Java, Ruby are used.
used.

No need of interaction with the


It is all about interacting with the servers.
server.

It reduces load on processing unit


It surge the processing load on the server.
of the server.

4
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

JAVASCRIPT

JavaScript: It is the most widely client side scripting or programming


language.
JavaScript is an object based oriented, dynamically typed (or also called
weakly typed) scripting language. It runs directly on the browser with the help of an
inbuilt interpreter.
Here, weakly typed means the variables are easily converted implicitly from
one data type to another.

2. VBScript: This scripting language is developed by Microsoft, based on the


Visual Basic. It is basically used to enhance the features of web pages in Internet
Explorer. VBScript is interpreted by Internet Explorer web browser.
3. jQuery: jQuery is a fast, small, lightweight JavaScript library. It is used to
facilitate a lot of JavaScript code into simple-to-use-functionality.
JAVASCRIPT

JavaScript is a dynamic computer programming language. It is lightweight


and most commonly used as a part of web pages, whose implementations allow
client-side script to interact with the user and make dynamic pages. It is an
interpreted programming language with object-oriented capabilities.

JavaScript was first known as LiveScript, but Netscape changed its name to
JavaScript, possibly because of the excitement being generated by Java. JavaScript
made its first appearance in Netscape 2.0 in 1995 with the name LiveScript. The
general-purpose core of the language has been embedded in Netscape, Internet
Explorer, and other web browsers.

5
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

FEATURES OF JAVASCRIPT

1.Lightweight & Interpreted


JavaScript is a lightweight scripting language that is executed directly in the
browser without the need for compilation.
2. Client-Side & Server-Side Execution
Initially, JavaScript was primarily used for client-side web development.
However, with environments like Node.js, it can also be used for server-side
development.
3. Dynamic Typing
JavaScript is dynamically typed, meaning variables do not require explicit
type definitions; their type is determined at runtime.
4. Prototype-Based Object Orientation
Unlike classical object-oriented languages, JavaScript uses prototypes
instead of classes for inheritance.
5. Event-Driven Programming
JavaScript supports event handling, which makes it great for developing
interactive web applications (e.g., handling clicks, mouse movements, and form
submissions).
6. Asynchronous & Single-Threaded
JavaScript is single-threaded but uses asynchronous programming (via
callbacks, promises, and async/await) to handle concurrent tasks efficiently.
7. Functional & Object-Oriented Programming
JavaScript supports both functional programming (higher-order functions,
closures) and object-oriented programming (prototypes, ES6 classes).
8. Cross-Browser Compatibility
JavaScript runs on all modern web browsers, making it a universal language
for web applications.
9. Manipulation of the DOM
JavaScript allows developers to dynamically manipulate HTML & CSS by
interacting with the Document Object Model (DOM).
10. Support for Modules
JavaScript now supports ES6 Modules, making it easier to structure large
applications.
11. Frameworks & Libraries
JavaScript has a vast ecosystem with powerful frameworks and libraries like
React, Angular, Vue.js, and Node.js.
6
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

12. Security Features


JavaScript includes security mechanisms like CORS (Cross-Origin Resource
Sharing) and Content Security Policy (CSP) to prevent attacks like Cross-Site
Scripting (XSS).

✓ JavaScript is a lightweight, interpreted programming language.


✓ Designed for creating network-centric applications.
✓ Complementary to and integrated with Java.
✓ Complementary to and integrated with HTML.
✓ Open and cross-platform
ADVANTAGES OF JAVASCRIPT

1. Speed & Performance

• JavaScript runs directly in the browser, reducing the need for server
communication.

2. Versatility & Full-Stack Development

• JavaScript can be used both on the client-side (browser) and server-side


(Node.js).

3. Easy to Learn & Use

• JavaScript has a simple syntax, making it beginner-friendly.


• It does not require installation, as all browsers support it by default.

4. Interactivity & Rich User Experience

• JavaScript enables dynamic content, animations, form validations, and


interactive elements.

5. Large Ecosystem & Community Support

• Huge community, with plenty of resources, tutorials, and forums.

7
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

6. Cross-Browser Compatibility

• Works across all modern browsers (Chrome, Firefox, Safari, Edge, etc.)..

7. Supports Asynchronous & Event-Driven Programming

• Ideal for real-time applications like chat apps and online gaming.

8. Integration with Other Technologies

• Works well with HTML & CSS for front-end development.

9. Regular Updates & Modern Features

Constant improvements make JavaScript more efficient and developer-


friendly.

10. Support for Mobile & Progressive Web Apps

• JavaScript enables responsive and mobile-friendly web applications.

11. Security & Authentication

12. Works Well with AI & Machine Learning

LIMITATIONS / DISADVANTAGES OF JAVASCRIPT

• Security Issues – JavaScript code is executed on the client-side, making it


vulnerable to security risks like cross-site scripting (XSS)
• Browser Compatibility – Different browsers interpret JavaScript differently,
which can lead to inconsistencies in behavior and appearance.
• Performance Limitations – Since JavaScript runs in the browser, it can be
slower than server-side languages, especially when handling complex
computations.
• Lack of Strong Typing – JavaScript is dynamically typed, which can lead to
unexpected errors and make debugging more challenging.
• No Multithreading – JavaScript runs in a single-threaded event loop, which
can cause performance bottlenecks when handling CPU-intensive tasks.

8
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

• Code Maintainability – Because JavaScript allows flexible coding styles,


large codebases can become difficult to maintain and debug.
• Client-Side Execution – Since JavaScript runs on the user’s machine, it can
be disabled or modified by the user, potentially breaking functionality.

STRUCTURE OF JAVA SCRIPT


SIMPLE JAVASCRIPT
<script type="text/javascript">
document.write("welcome to firsr JavaScript ");
</script>
OUTPUT

❖ The script tag specifies that we are using JavaScript.


❖ The text/javascript is the content type that provides information to the
browser about the data.
❖ The document.write() function is used to display dynamic content through
JavaScript.

Example of JavaScript that displays alert dialog box.

<script type="text/javascript">

alert("Hello welcome to JAVA SCRIPT");

</script>

9
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

OUTPUT

we are creating a function msg(). To create function in JavaScript, you need


to write function with function_name as given below.

To call function, you need to work on event. Here we are using onclick event
to call msg() function.

<html>
<head>
<script type="text/javascript">
function msg()
{
alert("EXAMPLE FOR JS FUNCTION");
}
</script>
</head>
<body>
<p>Welcome to JS using Function</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>

10
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

OUTPUT

JAVASCRIPT COMMENT

o The JavaScript comments are meaningful way to deliver message. It is


used to add information about the code, warnings or suggestions so that
end user can easily interpret the code.

o The JavaScript comment is ignored by the JavaScript engine i.e.


embedded in the browser.

Advantages of JavaScript comments.

o To make code easy to understand It can be used to elaborate the code


so that end user can easily understand the code.

o To avoid the unnecessary code It can also be used to avoid the code
being executed. Sometimes, we add the code to perform some action.
But after sometime, there may be need to disable the code. In such case,
it is better to use comments.

There are two types of comments in JavaScript.

1. Single-line Comment
2. Multi-line Comment

1. Single line Comment

11
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

It is represented by double forward slashes (//). It can be used before and


after the statement.

Example
<script>
// It is single line comment
document.write("hello javascript");
</script>
Example
<script>
var a=10;
var b=20;
var c=a+b;//It adds values of a and b variable
document.write(c);//prints sum of 10 and 20
</script>

2. Multi line Comment


It can be used to add single as well as multi line comments. So, it is more
convenient.
It is represented by forward slash with asterisk then asterisk with forward
slash. For example:

/* your code here */

It can be used before, after and middle of the statement.

Example
<script>
/* It is multi line comment.
It will not be displayed */
document.write("example of javascript multiline comment");
</script>

JAVASCRIPT VARIABLE

A JavaScript variable is simply a name of storage location. The actual value


of a variable can be changed at any time.

✓ Variables as Placeholders for unknown values:


12
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

They can be used in places where the values they represent are unknown
when the code is written.
✓ Variables as Code Clarifies
They can make the purpose of your code cleaner.

Rules of naming variables in JavaScript:

There are some rules while declaring a JavaScript variable (also known as
identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )


sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different
variables.

JavaScript's naming rules.

1. Using Case in Variables:


In JavaScript variables are case-sensitive. For Example: "total" and
"TOTAL" have different meanings in JavaScript.
The factors you need to consider when selecting variable names are case
sensitivity, invalid characters and the reserved words used in JavaScript.
In JavaScript variables are case-sensitive. For Example: "total" and
"TOTAL" have different meanings in JavaScript.
It is make sure that easier way to use lowercase letters.
If you are using a variable name with two words such as "total count". It's
better to capitalize the first letter of the word. For example. "Total_Count", etc.

2. Allowed special characters:


An important rule to remember is that variable name must start with a letter
(a to z or A to Z), underscore( _ ), or dollar( $ ) sign. For example: "_totalpay",
Total_Count etc.
After the first letter, we can use digits (0 to 9), for example: "value1".
3. Avoiding Reserved Words: When naming variables in JavaScript avoid the use
of the reserved word. For example: "if", "case" etc.

Declaring Variables:

13
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

To declare text as a variable, you can use the "var" or "let" keyword. The
Following syntax is used for declaring a variable in JavaScript:

Syntax:

Var variable_name;

In the above syntax, "var" is a keyword and "variable_name" is a name given to a


variable.

For Example:

var total_amount;

In the above example, "var" is a keyword and "total_amount" is a variable name.

Assign Value to Variables:

For assigning a value to a variable, you can use the JavaScript assignment operator
(=).

Syntax:

var variable_name = value;

In the above syntax, "var" is a keyword, "variable_name" is a name given to a


variable and value is used to assign a value to a variable.

For Example:

var total_amount = 500;

In the above example, "var" is a keyword, "total_amount" is a variable name and


500 is a value assigned to a variable.

Correct JavaScript variables


var x = 10;
var _value="sonoo";
14
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Incorrect JavaScript variables


var 123=30;
var *aa=320;

Example of JavaScript variable

<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>

Output

30

Types of Variables:

There are two types of variables in JavaScript:

1. Local variable
2. Global variable

1.Local variable

A JavaScript local variable is declared inside block or function. It is


accessible within the function or block only. For example:

<script>
function abc()
{
var x=10;//local variable
}
</script>
Or,

15
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

<script>
If(10<13)
{
var y=20;//JavaScript local variable
}
</script>

2.Global variable

A JavaScript global variable is accessible from any function. A variable i.e.


declared outside the function or declared with window object is known as global
variable. For example:

<script>
var data=200;//global variable
function a()
{
document.writeln(data);
}
function b()
{
document.writeln(data);
}
a();//calling JavaScript function
b();
</script>

Output

200 200

Declaring JavaScript global variable within function:

To declare JavaScript global variables inside function, we need window object


like window.value=250; Now it can be declared inside function and can be accessed
from any function.

16
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Example:

<script type="text/javascript">
function funl()
{
window.value=100;//declaring global variable by window object
}
function fun2()
{
funl();
alert("Value accessed at fun2 ="+window.value);// accessing global variable from
other function
}
fun2();
</script>

OUTPUT

JAVASCRIPT LITERALS

Fixed values are called literals. Numbers are written with or without decimals
like 23.4, 234 while Strings are written within double or single quotes like "Rama",
"Rama'.

The const keyword in JavaScript is used to turn an identifier as a constant or


literal. It produces a read-only reference to a value.

Syntax:

const VARIABLE NAME = value;

17
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

By standard naming conventions, the constant identifiers will be written in


capital letters.

The const keyword creates block-scoped identifiers whose alues cannot be


reassigned.

Variables created by the const keyword are immutable (i.e.) we are unable to
reassign them to different values else will rise error message.

Example:

const PI = 3.14

PI = 3.15 // will display error message

Variable declared using the const keyword must be initialized to a value


immediately failing which will cause Syntax error.

Example:

const AGE;// will give Syntax error

DATA TYPES IN JAVASCRIPT

• JavaScript provides different data types to hold different types of


values.
• A literal is a source code representation of a fixed value. A variable is
a value that can change, depending on conditions or on information
passed to the program.
• These are the type of values that can be stored and manipulated in a
programming language.

1. Primitive data type


2. Non-primitive (reference) data type

18
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

S.No. Datatype

1. String
Can contain groups of character as single value. It is represented in double
quotes.E.g. var x= “tutorial”.

2. Numbers
Contains the numbers with or without decimal. E.g. var x=44, y=44.56;

3. Booleans
Contain only two values either true or false. E.g. var x=true, y= false.

4. Undefined
Variable with no value is called Undefined. E.g. var x;

5. Null
If we assign null to a variable, it becomes empty. E.g. var x=null;

EXAMPLE

1.String

let s1 = "Hello There";


console.log(s1);
let s2 = 'Single quotes work fine';
console.log(s2);
let s3 = `can embed`;
console.log(s3);

Output

Hello There

19
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Single quotes work fine


can embed
2.Numbers

let n1 = 2;
console.log(n1)

let n2 = 1.3;
console.log(n2)

let n3 = Infinity;
console.log(n3)

let n4 = 'something here too' / 2;


console.log(n4)

2
1.3
Infinity
NaN

3.Booleans

let b1 = true;
console.log(b1);
let b2 = false;
console.log(b2);

Output
true
false

4.Undefined

let a;
console.log(a);

Output
Undefined
20
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

5. Null
let age = null;
console.log(age)
Output
Null
2. Non-primitive (reference) data type

The following table describes Non-Primitive Data Types in javaScript

Sr.No. Datatype Description

1. Array
Can contain groups of values of same type. E.g. var x={1,2,3,55};

2. Objects
Objects are stored in property and value pair. E.g. var rectangle = { length: 5,
breadth: 3};

1.ARRAYS
let a1 = [1, 2, 3, 4, 5];
console.log(a1);
let a2 = [1, "two", { name: "Object" }, [3, 4, 5]];
console.log(a2);

2.OBJECTS
let gfg = {
type: "Company",
location: "Noida"
}
console.log(gfg.type)

OUTPUT

Company

21
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

JAVASCRIPT OPERATORS

Operators are used to perform operation on one, two or more operands. Operator
is represented by a symbol such as +, =, *, % etc. Following are the operators
supported by java script

• Arithmetic Operators
• Comparison Operators
• Logical (or Relational) Operators
• Assignment Operators
• Conditional (or ternary) Operators
• Bitwise Operators
1.Arithmatic Operators

Following table shows all the arithmetic operators supported by javascript

Operator Description Example

+ Add two operands. 10 + 10 will give 20

- Subtract second operand from the 10 – 10 will give 0


first.

* Multiply two operands. 10 * 30 will give 300

/ Divide numerator by denominator 10/10 will give 1

22
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

% It is called modulus operator and 10 % 10 will give 0


gives remainder of the division.

++ Increment operator, increases 10 ++ will give 11


integer value by one

-- Decrement operator, decreases 10 – will give 9


integer value by one

Example
<script>
let x = 5;

// addition operator
document.write("Addition: x + 3 = ", x + 3);

// subtraction operator
document.write("Subtraction: x - 3 =", x - 3);

// multiplication operator
document.write("Multiplication: x * 3 =", x * 3);

// division operator
document.write("Division: x / 3 =", x / 3);

// remainder operator
document.write("Remainder: x % 3 =", x % 3);

// increment operator
document.write("Increment: ++x =", ++x);

23
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

// decrement operator
document.write("Decrement: --x =", --x);

// exponentiation operator
document.write("Exponentiation: x ** 3 =", x ** 3);
</script>

OUTPUT

Addition: x + 3 = 8
Subtraction: x - 3 = 2
Multiplication: x * 3 = 15
Division: x / 3 = 1.6666666666666667
Remainder: x % 3 = 2
Increment: ++x = 6
Decrement: --x = 5
Exponentiation: x ** 3 = 125

2.Comparison Operators or Relational Operator

This operatos are used to compares the values of two given opearands and gives the
result as Boolean(true/false)

Operator Description Example

== Checks if values of two operands are equal or 10 == 10 will give true


not, If yes then condition becomes true.

!= Not Equal to operator 10 !=10 will give false


Checks if the value of two operands is equal
or not, if values are not equal then condition
becomes true.

24
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

> GreaterThan operator 20 > 10 will give true


Checks if the value of left operand is greater
than the value of right operand, if yes then
condition becomes true.

< Less than operator 10 < 20 will give true


Checks if the value of left operand is less than
the value of right operand, if yes then
condition becomes true.

>= Greater than or equal to operator 10 >=20 will give false


Checks if the value of left operand is greater
than or equal to the value of right operand, if
yes then condition becomes true.

<= Less than or equal to operator 10 <=20 will give true.


Checks if the value of left operand is less than
or equal to the value of right operand, if yes
then condition becomes true.

Example:
// equal to operator
console.log("Equal to: 2 == 2 is", 2 == 2);

// not equal operator


console.log("Not equal to: 3 != 3 is", 3 != 3);

// strictly equal to operator


25
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

console.log("Strictly equal to: 2 === '2' is", 2 === '2');

// strictly not equal to operator


console.log("Strictly not equal to: 2 !== '2' is", 2 !== '2');

// greater than operator


console.log("Greater than: 3 > 3 is", 3 > 3);

// less than operator


console.log("Less than: 2 > 2 is", 2 > 2);

// greater than or equal to operator


console.log("Greater than or equal to: 3 >= 3 is", 3 >= 3);

// less than or equal to operator


console.log("Less than or equal to: 2 <= 2 is", 2 <= 2);

OUTPUT

Equal to: 2 == 2 is true


Not equal to: 3 != 3 is false
Strictly equal to: 2 === '2' is false
Strictly not equal to: 2 !== '2' is true
Greater than: 3 > 3 is false
Less than: 2 > 2 is false
Greater than or equal to: 3 >= 3 is true
Less than or equal to: 2 <= 2 is true

3.Logical Operators
This operatos are used to compares the values of two given relational expression and
gives the result as Boolean(true/false). It also used to combine more than one
relational expression.

26
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Operator Description Example

&& Logical AND operator returns true if both operands 10 && 10 will give
are non zero. true.

|| Logical OR operator returns true If any of the 10 || 0 will give true.


operand is non zero

! Logical NOT operator complements the logical ! (10 && 10) will
state of its operand. give false.

let x = 3;

// logical AND
console.log((x < 5) && (x > 0)); // true
console.log((x < 5) && (x > 6)); // false

// logical OR
console.log((x > 2) || (x > 5)); // true
console.log((x > 3) || (x < 0)); // false

// logical NOT
console.log(!(x == 3)); // false
console.log(!(x < 2)); // true

27
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

4.Assignment Operators

Operator Description Example

= Simple Assignment operator C = A + B will assign


Assigns values from right side operands to left value of A + B into C
side operand.

+= Add AND assignment operator C += A is equivalent


It adds right operand to the left operand and to C = C + A
assign the result to left operand

-= Subtract AND assignment operator C -= A is equivalent


It subtracts right operand from the left operand to C = C - A
and assign the result to left operand

*= Multiply AND assignment operator C *= A is equivalent


It multiplies right operand with the left to C = C * A
operand and assign the result to left operand

/= Divide AND assignment operator C /= A is equivalent to


It divides left operand with the right operand C = C / A
and assign the result to left operand

28
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

%= Modulus AND assignment operator C %= A is equivalent


Modulus AND assignment operator, It takes to C = C % A
modulus using two operands and assign the
result to left operand

// assignment operator
let a = 7;
console.log("Assignment: a = 7, a =", a);

// addition assignment operator


a += 5; // a = a + 5
console.log("Addition Assignment: a += 5, a =", a);

// subtraction assignment operator


a -= 5; // a = a - 5
console.log("Subtraction Assignment: a -= 5, a =", a);

// multiplication assignment operator


a *= 2; // a = a * 2
console.log("Multiplication Assignment: a *= 2, a =", a);

// division assignment operator


a /= 2; // a = a / 2
console.log("Division Assignment: a /= 2, a =", a);

// remainder assignment operator


a %= 2; // a = a % 2
console.log("Remainder Assignment: a %= 2, a =", a);

// exponentiation assignment operator


a **= 2; // a = a**2
console.log("Exponentiation Assignment: a **= 7, a =", a);

OUTPUT

29
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Assignment: a = 7, a = 7
Addition Assignment: a += 5, a = 12
Subtraction Assignment: a -= 5, a = 7
Multiplication Assignment: a *= 2, a = 14
Division Assignment: a /= 2, a = 7
Remainder Assignment: a %= 2, a = 1
Exponentiation Assignment: a **= 7, a = 1

5.Conditional Operator / Ternary operator

The Ternary Operator in JavaScript is a shortcut for writing simple if-else


statements. It’s also known as the Conditional Operator because it works based on
a condition. The ternary operator allows you to quickly decide between two values
depending on whether a condition is true or false.

It is also called ternary operator, since it has three operands.

EXAMPLE

let PMarks = 50;


let res = (PMarks > 39) ? "Pass" : "Fail";
console.log(res);

OUTPUT

pass

Operator Description Example

?: Conditional If Condition is true? Then value X : Otherwise value


Expression Y

30
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

6.BITWISE OPERATORS

&(Bitwise AND) :Performs Boolean AND operation on each bit of its operands.

| (BitWise OR) : Performs Boolean OR operation on each bit of its operands.

^ (Bitwise XOR) :Performs Boolean XOR operation on each bit of its operands.

~ (Bitwise Not) :Reverses 1 to 0 and 0 to 1 in the given operand

<<(Left Shift) : It moves all the bits in its first operand to the left by the number of
places specified as the second operand. Empty bits are filled with zeros

>> (Right Shift) :It moves all the bits in its first operand to the right by the number
of places specified as the second operand Empty bits are filled with zeros.

31
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

FUNCTIONS IN JAVASCRIPT

JAVASCRIPT BUILT-IN FUNCTIONS

1.Number Methods
The Number object contains only the default methods that are part of every
object's definition.
Method & Description

constructor()
Returns the function that created this object's instance.
By default this is the Number object.

toPrecision()

Defines how many total digits (including digits to the left


and right of the decimal) to display of a number.

toString()
Returns the string representation of the number's value.

valueOf()
Returns the number's value.

2.STRING METHODS

Here is a list of each method and its description.


. Method & Description
charAt()
Returns the character at the specified index.

concat()
Combines the text of two strings and returns a new string.

indexOf()
Returns the index within the calling String object of the first
occurrence of the specified value, or -1 if not found.

32
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

lastIndexOf()
Returns the index within the calling String object of the last
occurrence of the specified value, or -1 if not found.

length()
Returns the length of the string.

replace()
Used to find a match between a regular expression and a string, and to replace
the matched substring with a new substring.

earch()
Executes the search for a match between a regular expression and a specified string.

substr()
Returns the characters in a string beginning at the specified location
through the specified number of characters.

substring()
Returns the characters in a string between two indexes into the string.
toLocaleLowerCase()
The characters within a string are converted to lower case while respecting the current
locale.

toLowerCase()
Returns the calling string value converted to lower case.

toString()
Returns a string representing the specified object.

33
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

toUpperCase()
Returns the calling string value converted to uppercase.

3.Array Methods

Here is a list of each method and its description.


Sr.No. Method & Description

concat()
1 Returns a new array comprised of this array joined with other array(s) and/or
value(s).

every()
2
Returns true if every element in this array satisfies the provided testing function.

filter()
3 Creates a new array with all of the elements of this array for which the provided
filtering function returns true.

forEach()
4
Calls a function for each element in the array.

indexOf()
5 Returns the first (least) index of an element within the array equal
to the specified value, or -1 if none is found.

join()
6
Joins all elements of an array into a string.
4.Date Methods

Here is a list of each method and its description.


Sr.No. Method & Description

Date()
1
Returns today's date and time

2 getDate()

34
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Returns the day of the month for the specified date according to local time.

getDay()
3
Returns the day of the week for the specified date according to local time.

getFullYear()
4
Returns the year of the specified date according to local time.

getHours()
5
Returns the hour in the specified date according to local time.
5.Math Methods

Here is a list of each method and its description.


Sr.No. Method & Description

abs()
1
Returns the absolute value of a number.

acos()
2
Returns the arccosine (in radians) of a number.

asin()
3
Returns the arcsine (in radians) of a number.

atan()
4
Returns the arctangent (in radians) of a number.

atan2()
5
Returns the arctangent of the quotient of its arguments.

ceil()
6
Returns the smallest integer greater than or equal to a number.

cos()
7
Returns the cosine of a number.

exp()
8 Returns EN, where N is the argument, and E is Euler's constant, the base of the
natural logarithm.

35
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

floor()
9
Returns the largest integer less than or equal to a number.

log()
10
Returns the natural logarithm (base E) of a number.

USER DEFINED FUNCTIONS

Functions in JavaScript are reusable blocks of code designed to perform


specific tasks. They allow you to organize, reuse, and modularize code. It can take
inputs, perform actions, and return outputs.

Declare A Function /Syntax

function functionName([arg1, arg2, ...argN])


{
//code to be executed
}

Function with Return Value

<script>
function sum(x, y)
{
return x + y;
}
document.write(sum(6, 9));
</script>

OUTPUT

15

Function Syntax and Working

• A function definition is sometimes also termed a function declaration


or function statement. Below are the rules for creating a function in
JavaScript:

36
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

• Begin with the keyword function followed by,


• A user-defined function name (In the above example, the name
is sum)
• A list of parameters enclosed within parentheses and separated by
commas (In the above example, parameters are x and y)
• A list of statements composing the body of the function enclosed
within curly braces {} (In the above example, the statement is “return
x + y”).

Function Parameters

Parameters are input passed to a function. In the above example, sum() takes
two parameters, x and y.

Calling Functions

After defining a function, the next step is to call them to make use of the
function. We can call a function by using the function name separated by the value
of parameters enclosed between the parenthesis.

<script>
// Function Definition
function welcomeMsg(name)
{
return ("Hello " + name + " welcome to Functions");
}

let nameVal = "User";

// calling the function


document.write(welcomeMsg(nameVal));

</script>

OUTPUT

Hello User welcome to Functions

37
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

<script>
var add=new Function("num1","num2","return num1+num2");
document.writeln(add(2,5));
</script>

OUTPUT 7

Advantage of JavaScript function

o Code reusability: We can call a function several times in a script to


perform their tasks so it saves coding.
o Less coding: It makes our program compact. We don't need to write
many lines of code each time to perform a common task.
o Functions can be used multiple times, reducing redundancy.
o Break down complex problems into manageable pieces.
o Manage complexity by hiding implementation details.
o Can call themselves to solve problems recursively.

CONTROL STATEMENTS IN JAVASCRIPT

JavaScript control statement is used to control the execution of a program


based on a specific condition. If the condition meets then a particular block of
action will be executed otherwise it will execute another block of action that
satisfies that particular condition.

38
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

1.JavaScript If-else

The JavaScript if-else statement is used to execute the code whether


condition is true or false. There are three forms of if statement in JavaScript.

1. If Statement
2. If else statement
3. if else if statement

JavaScript If statement

It evaluates the content only if expression is true. The signature of JavaScript


if statement is given below.

SYNTAX

if(expression)
{
//content to be evaluated
}

EXAMPLE

<script>
var a=20;
if(a>10)
{
document.write("value of a is greater than 10");
}
</script>

OUTPUT

value of a is greater than 10

If...else Statement

It evaluates the content whether condition is true of false. The syntax of


JavaScript if-else statement is given below.
39
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

SYNTAX

if(expression)
{
//content to be evaluated if condition is true
}
Else
{
//content to be evaluated if condition is false
}

EXAMPLE

<script>
var a=20;
if(a%2==0)
{
document.write("a is even number");
}
Else
{
document.write("a is odd number");
}
</script>

OUTPUT

a is even number

If...else if statement
It evaluates the content only if expression is true from several expressions.
The signature of JavaScript if else if statement is given below.

SYNTAX

if(expression1)
{
//content to be evaluated if expression1 is true
40
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

}
else if(expression2)
{
//content to be evaluated if expression2 is true
}
else if(expression3)
{
//content to be evaluated if expression3 is true
}
Else
{
//content to be evaluated if no expression is true
}

EXAMPLE

<script>
var a=20;
if(a==10){
document.write("a is equal to 10");
}
else if(a==15){
document.write("a is equal to 15");
}
else if(a==20){
document.write("a is equal to 20");
}
else{
document.write("a is not equal to 10, 15 or 20");
}
</script>

OUTPUT

a is equal to 20

41
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

SWITCH CASE
switch case is a conditional statement that is used so it can provide a way to
execute the statements based on their conditions or different conditions.

Syntax
switch (expression)
{
case value1:
Code to be executed;
break;
Case value2:
code to be executed;
break;
.........
default:
Code to be executed if the above values are not matched;
}

EXAMPLE

const expression = 'Apple';


switch (expression){
case 'Oranges':
console.log('I prefer Oranges');
break;
case 'watermelons':
console.log('I prefer watermelon too!');
break;
case 'Apple':
console.log('One apple a day keeps the doctor away);
break;
default:
console.log(`Sorry, we are out of ${expression}`);
}

OUTPUT

One apple a day keeps the doctor away

42
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Break Statement

A break keyword is used within the switch case statement this statement
indicates the end of a particular case of the switch statement

Default Statement

In JavaScript, a default keyword is used in a switch statement to define the


default expression. In JavaScript, when any case doesn't match with the expression
of the switch-case statement then it will execute the default code block.

Loops / Iterative statements.

The JavaScript loops are used to iterate the piece of code using for, while, do
while or for-in loops. It makes the code compact. It is mostly used in array. It is also
called iterative statements.

Advantages of using Loop:

• It perform repetitive task with less number of codes.

There are four types of loops in JavaScript.

1. For loop
2. while loop
3. do while loop
4. for in loop

1.For loop

The JavaScript for loop iterates the elements for the fixed number of times. It
should be used if number of iteration is known. It executes a block of code until a
specified condition is true.

SYNTAX

43
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

for (initialization; condition; increment)


{
code to be executed
}

• Initialize: This is an expression that starts the loop.


• condition: This is a Boolean expression that specifies whether the loop should
execute a loop or not.
• Increment/Decrement: Executes the iterate (i.e. increment and decrement)
after each iteration of the for loop statement.

EXAMPLE

<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script>

OUTPUT

1
2
3
4
5

2.while loop

The JavaScript while loop iterates the elements for the infinite number of
times. It should be used if number of iteration is not known. In the while loop, the
condition is first checked and if it evaluates to TRUE, the statements inside the curly
braces are executed.

44
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

while (condition)

code to be executed

EXAMPLE
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script>

OUTPUT

11
12
13
14
15

3.Do while loop


The JavaScript do while loop iterates the elements for the infinite number
of times like while loop. But, code is executed at least once whether condition is true
or false.
It is also called an exit controlled looping statement because the test
condition is checked at the end of the do-while loop and hence the body is executed
unconditionally for the first time.

SYNTAX

do
{

45
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

code to be executed
}while (condition);
EXAMPLE

<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script>

OUTPUT

21
22
23
24
25

4.For in loop

The JavaScript for in loop is used to iterate the properties of an object.


JavaScript provides a variation of a loop known as a for loop that can be used to
extract the names and values of any object. It allows looping through all elements of
an array or properties of an object.

syntax

for ( v_name in object_name)


{
statements(s);
}

EXAMPLE

<html>
<body>
<h1>JavaScript Arrays</h1>
46
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

<h2>For In Loops</h2>
<p>The for in statement can loops over array values:</p>
<p id="demo"></p>

<script>
const numbers = [45, 4, 9, 16, 25];

let txt = "";


for (let x in numbers) {
txt += numbers[x] + "<br>";
}

document.getElementById("demo").innerHTML = txt;
</script>

</body>
</html>

OUTPUT

JavaScript Arrays
For In Loops

The for in statement can loops over array values:

45
4
9
16
25

BREAK

The break statement can also be used to jump out of a loop

<html>
<body>
<h2>JavaScript Loops</h2>
<p>A loop with a <b>break</b> statement.</p>

47
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

<p id="demo"></p>
<script>
let text = "";
for (let i = 0; i < 10; i++)
{
if (i === 3)
{
break;
}
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

OUTPUT

JavaScript Loops
A loop with a break statement.

The number is 0
The number is 1
The number is 2

CONTINUE STATEMENT

The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

<html>
<body>
<h2>JavaScript Loops</h2>
<p>A loop with a <b>continue</b> statement.</p>
<p>A loop which will skip the step where i = 3.</p>
<p id="demo"></p>
<script>
let text = "";

48
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

for (let i = 0; i < 10; i++) {


if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>

OUTPUT

JavaScript Loops

A loop with a continue statement.

A loop which will skip the step where i = 3.

The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9

ADVANCE SCRIPT

BUILT IN OBJECTS

WINDOW OBJECT

Property Description

closed Returns a boolean true if a window is closed.

console Returns the Console Object for the window.


See also The Console Object.

49
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

defaultStatus Deprecated.

document Returns the Document object for the window.


See also The Document Object.

Window Object Methods

Method Description

addEventListener() Attaches an event handler to the window

alert() Displays an alert box with a message and an


OK button

atob() Decodes a base-64 encoded string

blur() Removes focus from the current window

DOM DOCUMENT OBJECT

The document object represents your web page.

If you want to access any element in an HTML page, you always start with
accessing the document object.

Finding HTML Elements


Method Description

document.getElementById(id) Find an element by


element id

document.getElementsByTagNam Find elements by tag


e(name) name

document.getElementsByClassNa Find elements by class


me(name) name

50
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Changing HTML Elements


Property Description

element.innerHTML = new html content Change the


inner HTML of
an element

element.attribute = new value Change the


attribute value
of an HTML
element

element.style.property = new style Change the


style of an
HTML element

Method Description

element.setAttribute(attribute, value) Change the


attribute value
of an HTML
element

Adding and Deleting Elements


Method Description

document.createElement(element) Create an
HTML
element

document.removeChild(element) Remove an
HTML
element

document.appendChild(element) Add an
HTML
element

51
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

document.replaceChild(new, old) Replace an


HTML
element

document.write(text) Write into


the HTML
output
stream

HISTORY OBJECT PROPERTIES AND METHODS


Property/Method Description

back() Loads the previous URL (page) in


the history list

forward() Loads the next URL (page) in the


history list

go() Loads a specific URL (page)


from the history list

length Returns the number of URLs


(pages) in the history list

SCREEN OBJECT PROPERTIES

Property Description

availHeight Returns the height of the screen (excluding


the Windows Taskbar)

availWidth Returns the width of the screen (excluding


the Windows Taskbar)

colorDepth Returns the bit depth of the color palette for


displaying images

height Returns the total height of the screen

52
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

pixelDepth Returns the color resolution (in bits per


pixel) of the screen

width Returns the total width of the screen

NAVIGATOR OBJECT PROPERTIES

Property Description

appCodeName Returns browser code name

appName Returns browser name

appVersion Returns browser version

LOCATION OBJECT PROPERTIES

Property Description

hash Sets or returns the anchor part (#)


of a URL

host Sets or returns the hostname and


port number of a URL

hostname Sets or returns the hostname of a


URL

href Sets or returns the entire URL

origin Returns the protocol, hostname and


port number of a URL

pathname Sets or returns the path name of a


URL

FORM OBJECT PROPERTIES

53
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Property Description

acceptCharset Sets or returns the value of the


accept-charset attribute in a form

action Sets or returns the value of the


action attribute in a form

autocomplete Sets or returns the value of the


autocomplete attribute in a form

encoding Alias of enctype

BROWSER OBJECT

window.open() - open a new window


window.close() - close the current window
window.moveTo() - move the current window
window.resizeTo() - resize the current window

NUMBER OBJECT

Method Description

toString() Returns a number as a string

toExponential() Returns a number written in exponential


notation

toFixed() Returns a number written with a number


of decimals

toPrecision() Returns a number written with a


specified length

valueOf() Returns a number as a number

54
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

USER DEFINED OBJECTS

A javaScript object is an entity having state and behavior (properties and


method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.

JavaScript is an object-based language. Everything is an object in


JavaScript.

JavaScript is template based not class based. Here, we don't create class to
get the object. But, we direct create objects.

Creating Objects in JavaScript

There are 3 ways to create objects.

1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)

1) JavaScript Object by object literal

The syntax of creating object using object literal is given below:

object={property1:value1,property2:value2.....propertyN:valueN}

property and value is separated by : (colon).

<script>
emp={id:102,name:"Shyam Kumar",salary:40000}
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Output

55
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

102 Shyam Kumar 40000

2) By creating instance of Object

The syntax of creating object directly is given below:

var objectname=new Object();

Here, new keyword is used to create object.

example of creating object directly.

<script>
var emp=new Object();
emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>

Output

101 Ravi 50000

3) By using an Object constructor

Here, you need to create function with arguments. Each argument value can
be assigned in the current object by using this keyword.

The this keyword refers to the current object.

The example of creating object by object constructor is given below.

<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary;
56
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

}
e=new emp(103,"Vimal Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>

Output

103 Vimal Jaiswal 30000

Defining method in JavaScript Object

We can define method in JavaScript object. But before defining method, we


need to add property in the function with same name as method.

<script>
function emp(id,name,salary)
{
this.id=id;
this.name=name;
this.salary=salary;
this.changeSalary=changeSalary;
function changeSalary(otherSalary)
{
this.salary=otherSalary;
}
}
e=new emp(103,"Sonoo Jaiswal",30000);
document.write(e.id+" "+e.name+" "+e.salary);
e.changeSalary(45000);
document.write("<br>"+e.id+" "+e.name+" "+e.salary);
</script>

Output

103 Sonoo Jaiswal 30000


103 Sonoo Jaiswal 45000

57
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

DOM AND WEB BROWSER ENVIRONMENTS

JavaScript interacts with web pages through the DOM (Document Object
Model) and various Web APIs provided by the browser.

DOM
The Document Object Model (DOM) represents an HTML document as a
structured tree of objects, where each HTML element is a node that JavaScript can
manipulate.

Key Components of the DOM:

Document (document) – The root object representing the webpage.


Elements (Element nodes) – Represent HTML tags like <div>, <p>, <button>, etc.
Attributes (Attribute nodes) – Represent attributes of elements like id, class, href,
etc.
Text (Text nodes) – Represents text inside elements.
Comments (Comment nodes) – Represents HTML comments.

Example of a simple DOM tree:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<h1 id="heading">Hello, DOM!</h1>
<p class="text">This is a paragraph.</p>
</body>
</html>
This structure is represented as:
Document
├── <html>
│ ├── <head>
│ │ ├── <title>Page Title</title>
58
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

│ ├── <body>
│ │ ├── <h1 id="heading">Hello, DOM!</h1>
│ │ ├── <p class="text">This is a paragraph.</p>
2. Manipulating the DOM with JavaScript

JavaScript allows dynamic interaction with the DOM using document


methods.

let heading = document.getElementById("heading"); // Select by ID


let paragraphs = document.getElementsByClassName("text"); // Select by Class
let allParas = document.getElementsByTagName("p"); // Select by Tag Name
let firstPara = document.querySelector(".text"); // Select first matching element
let allTexts = document.querySelectorAll(".text"); // Select all matching elements

heading.textContent = "Hello, JavaScript!"; // Change text


heading.style.color = "blue"; // Change CSS
heading.setAttribute("class", "new-class"); // Modify attribute

Creating and Removing Elements

let newDiv = document.createElement("div"); // Create a new div


newDiv.textContent = "This is a new div";
document.body.appendChild(newDiv); // Append to the body

document.body.removeChild(newDiv); // Remove element

3. Web Browser Environment

The browser provides built-in objects and APIs to interact with webpages
beyond the DOM.

Key Browser Objects:

window – The global object representing the browser window.


document – Represents the current webpage (DOM).
navigator – Provides information about the user's browser and OS.
location – Provides URL information and navigation controls.
history – Manages the browser's session history.
console – Allows logging and debugging.
59
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Examples of Browser Object Usage

1. Window & Document

console.log(window.innerWidth); // Get browser width


console.log(document.title); // Get document title

2. Location & Navigation

console.log(location.href); // Get the current URL


// location.reload(); // Reload the page
// location.assign("https://www.google.com");

3. Navigator (Browser Info)

console.log(navigator.userAgent); // Get browser details


console.log(navigator.language); // Get user language

4. History (Browsing History)

console.log(history.length); // Get history length


// history.back(); // Go back one page
// history.forward(); // Go forward one page

FORMS AND VALIDATIONS

JavaScript validations help ensure that user inputs meet the expected format
before being processed. This improves user experience and prevents invalid or
harmful data submission.

Types of JavaScript Validations

1. Client-Side Validation – Performed in the browser before sending data to


the server.
2. Server-Side Validation – Performed on the server to prevent malicious
inputs.

60
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

Client-side validation is faster and provides immediate feedback, but it should


never replace server-side validation for security reasons.

Types of Input Validations

1. Required Field Validation


2. String Length Validation
3. Email Validation
4. Phone Number Validation
5. Password Strength Validation
6. Number & Range Validation

JavaScript Validation Examples

1. Required Field Validation

Ensures that the user does not leave a field empty.

function validateRequired() {
let name = document.getElementById("name").value;
if (name.trim() === "") {
alert("Name is required!");
return false;
}

2.String Length Validation

Ensures input is within a specified length.

function validateLength() {
let username = document.getElementById("username").value;
if (username.length < 5 || username.length > 15) {
alert("Username must be between 5 and 15 characters.");
return false;
}
return true;
}

61
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

3.Email Validation

Validates an email format using regular expressions.

function validateEmail() {
let email = document.getElementById("email").value;
let regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!regex.test(email)) {
alert("Invalid email format!");
return false;
}
return true;
}

3. Phone Number Validation

Checks if the phone number is in a valid format (example: US phone number).

function validatePhone() {
let phone = document.getElementById("phone").value;
let regex = /^\d{10}$/; // 10-digit phone number
if (!regex.test(phone)) {
alert("Invalid phone number! Must be 10 digits.");
return false;
}
return true;

4.Password Strength Validation

Ensures the password contains at least one uppercase letter, one lowercase letter,
one digit, and one special character.

function validatePassword() {
let password = document.getElementById("password").value;
let regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-
z\d@$!%*?&]{8,}$/;
if (!regex.test(password)) {
alert("Password must be at least 8 characters long and include an uppercase,
lowercase, digit, and special character.");
62
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

return false;
}

5.Form Validation Example


Combining multiple validation functions in an HTML form.

<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<script>
function validateForm() {
return validateRequired() && validateEmail() && validatePassword();
}

function validateRequired() {
let name = document.getElementById("name").value;
if (name.trim() === "") {
alert("Name is required!");
return false;
}
return true;
}

function validateEmail() {
let email = document.getElementById("email").value;
let regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!regex.test(email)) {
alert("Invalid email format!");
return false;
}
return true;
}

function validatePassword() {
let password = document.getElementById("password").value;
let regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-
z\d@$!%*?&]{8,}$/;
63
APOLLO ARTS AND SCIENCE COLLEGE CHENNAI
UNIT IV WEB DESIGN AND DEVELOPMENT

if (!regex.test(password)) {
alert("Password must contain an uppercase, lowercase, digit, and special
character.");
return false;
}
return true;
}
</script>
</head>
<body>
<form onsubmit="return validateForm()">
<label for="name">Name:</label>
<input type="text" id="name"><br>

<label for="email">Email:</label>
<input type="email" id="email"><br>

<label for="password">Password:</label>
<input type="password" id="password"><br>

<button type="submit">Submit</button>
</form>
</body>
</html>

64

You might also like