0% found this document useful (0 votes)
2 views39 pages

Wad Module 3 Notes

JavaScript is a widely-used scripting language for web development, enabling interactivity and functionality in HTML pages. It allows for dynamic content, form validation, and browser detection, among other features. The document covers JavaScript variables, data types, operators, conditional statements, and looping structures, providing foundational knowledge for programming in JavaScript.

Uploaded by

rashmidivantgi
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)
2 views39 pages

Wad Module 3 Notes

JavaScript is a widely-used scripting language for web development, enabling interactivity and functionality in HTML pages. It allows for dynamic content, form validation, and browser detection, among other features. The document covers JavaScript variables, data types, operators, conditional statements, and looping structures, providing foundational knowledge for programming in JavaScript.

Uploaded by

rashmidivantgi
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

JAVASCRIPT Notes

JAVASCRIPT

JavaScript is the scripting language of the Web.


JavaScript is used in millions of Web pages to add functionality, validate forms, detect browsers, and

much more.
Introduction to JavaScript

JavaScript is used in millions of Web pages to improve the design, validate forms, detect browsers, create
cookies, and much more.
JavaScript is the most popular scripting language on the Internet, and works in all major browsers, such as

Internet Explorer, Mozilla Firefox, and Opera.


What is JavaScript?

JavaScript was designed to add interactivity to HTML pages


JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts execute without preliminary compilation)
Everyone can use JavaScript without purchasing a license
Java and JavaScript are two completely different languages in both concept and design!

Java (developed by Sun Microsystems) is a powerful and much more complex programming language - in

the same category as C and C++.


What can a JavaScript Do ?

JavaScript gives HTML designers a programming tool - HTML authors are normally not
programmers, but JavaScript is a scripting language with a very simple syntax! Almost anyone can
put small "snippets" of code into their HTML pages
JavaScript can put dynamic text into an HTML page - A JavaScript statement like this:
[Link]("<h1>" + name + "</h1>") can write a variable text into an HTML page
JavaScript can react to events - A JavaScript can be set to execute when something happens,
like when a page has finished loading or when a user clicks on an HTML element
JavaScript can read and write HTML elements - A JavaScript can read and change the content
of an HTML element
JavaScript can be used to validate data - A JavaScript can be used to validate form data before
it is submitted to a server. This saves the server from extra processing
JavaScript can be used to detect the visitor's browser - A JavaScript can be used to detect the
visitor's browser, and - depending on the browser - load another page specifically designed for that
browser

Page 1
JAVASCRIPT Notes
JavaScript can be used to create cookies - A JavaScript can be used to store and retrieve
information on the visitor's computer.
JavaScript Variables

Variables are "containers" for storing information.

JavaScript variables are used to hold values or expressions.

A variable can have a short name, like x, or a more descriptive name, like carname.

Rules for JavaScript variable names:

Variable names are case sensitive (y and Y are two different variables)
Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Example

A variable's value can change during the execution of a script. You can refer to a variable by its name to
display or change its value.
<html>

<body>
<script type="text/javascript">
var firstname;
firstname="Welcome";
[Link](firstname);
[Link]("<br />");
firstname="XYZ";
[Link](firstname);
</script>

<p>The script above declares a variable,


assigns a value to it, displays the value, change the value,
and displays the value again.</p>

</body>
</html>
Output :

Welcome
XYZ
The script above declares a variable, assigns a value to it, displays the value, change the value, and

displays the value again.

Page 2
JAVASCRIPT Notes
Declaring (Creating) JavaScript Variables
Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var statement:

var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).

However, you can also assign values to the variables when you declare them:

var x=5;
var carname="Scorpio";

After the execution of the statements above, the variable x will hold the value 5, and carname will hold
the value Scorpio.
Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables will automatically be
declared.
These statements:

x=5;
carname="Scorpio";

have the same effect as:

var x=5;
var carname="Scorpio";

Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;
var x;

Page 3
JAVASCRIPT Notes
After the execution of the statements above, the variable x will still have the value of 5. The value of x is
not reset (or cleared) when you redeclare it.

Page 4
JAVASCRIPT Notes

DataTypes

Numbers - are values that can be processed and calculated. You don't enclose them in quotation
marks. The numbers can be either positive or negative.
Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses the string
literally; it doesn't process it. You'll use strings for text you want displayed or values you want
passed along.
Boolean (true/false) - lets you evaluate whether a condition meets or does not meet specified
criteria.
Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number, whereas null is
the absence of any value.

Data Types

TYPE EXAMPLE
Numbers Any number, such as 17, 21, or 54e7

Strings "Greetings!" or "Fun"

Boolean Either true or false

Null A special keyword for exactly that – the null value (that is, nothing)

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:

y=x-5;
z=y+5;

JavaScript Operators

The operator = is used to assign values.

The operator + is used to add values.

The assignment operator = is used to assign values to JavaScript variables.

The arithmetic operator + is used to add values together.

y=5;
z=2;
x=y+z;

Page 5
JAVASCRIPT Notes
The value of x, after the execution of the statements above is 7.
JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y=5, the table below explains the arithmetic operators:

Operator Description Example Result


+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4

JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x=10 and y=5, the table below explains the assignment operators:

Operator Example Same As Result


= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

The + Operator Used on Strings


The + operator can also be used to add string variables or text values together.

To add two or more string variables together, use the + operator.

txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;

Page 6
JAVASCRIPT Notes
After the execution of the statements above, the variable txt3 contains "What a verynice day".

To add a space between the two strings, insert a space into one of the strings:

txt1="What a very ";


txt2="nice day";
txt3=txt1+txt2;

or insert a space into the expression:

txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;

After the execution of the statements above, the variable txt3 contains:

"What a very nice day"

Adding Strings and Numbers


Look at these examples:

x=5+5;
[Link](x);

x="5"+"5";
[Link](x);

x=5+"5";
[Link](x);

x="5"+5;
[Link](x);

The rule is:


If you add a number and a string, the result will be a string.

JavaScript Comparison and Logical Operators

Comparison and Logical operators are used to test for true or false.

Page 7
JAVASCRIPT Notes
Comparison Operators
Comparison operators are used in logical statements to determine equality or difference between variables
or values.
Given that x=5, the table below explains the comparison operators:

Operator Description Example


== is equal to x==8 is false
=== is exactly equal to (value and type) x===5 is true
x==="5" is false
!= is not equal x!=8 is true
> is greater than x>8 is false
< is less than x<8 is true
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true

How Can it be Used


Comparison operators can be used in conditional statements to compare values and take action depending

on the result:

if (age<18) [Link]("Too young");

You will learn more about the use of conditional statements in the next chapter of this tutorial.
Logical Operators

Logical operators are used to determine the logic between variables or values.

Given that x=6 and y=3, the table below explains the logical operators:

Operator Description Example


&& and (x < 10 && y > 1) is true
|| or (x==5 || y==5) is false
! not !(x==y) is true

Conditional Operator
JavaScript also contains a conditional operator that assigns a value to a variable based on some condition.

Page 8
JAVASCRIPT Notes
Syntax
variablename=(condition)?value1:value2

Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable greeting will be assigned the value
"Dear President " else it will be assigned "Dear".

Conditional Statements

Very often when you write code, you want to perform different actions for different decisions. You can
use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:

if statement - use this statement if you want to execute some code only if a specified condition is
true
if...else statement - use this statement if you want to execute some code if the condition is true
and another code if the condition is false
if...else if ....else statement - use this statement if you want to select one of many blocks of code to
be executed
switch statement - use this statement if you want to select one of many blocks of code to be
executed
If Statement

You should use the if statement if you want to execute some code only if a specified condition is true.

Syntax

if (condition)
{
code to be executed if condition is true
}

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript error!
Example 1

<script type="text/javascript">
//Write a "Good morning" greeting if
//the time is less than 10
var d=new Date();
var time=[Link]();

Page 9
JAVASCRIPT Notes
if (time<10)
{
[Link]("<b>Good morning</b>");
}
</script>

Example 2
<script type="text/javascript">
//Write "Lunch-time!" if the time is 11
var d=new Date();
var time=[Link]();

if (time==11)
{
[Link]("<b>Lunch-time!</b>");
}
</script>

Note: When comparing variables you must always use two equals signs next to each other (==)!
Notice that there is no ..else.. in this syntax. You just tell the code to execute some code only if the

specified condition is true.


If...else Statement

If you want to execute some code if a condition is true and another code if the condition is not true, use

the if ... else statement.


Syntax

if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example
<script type="text/javascript">
//If the time is less than 10,
//you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.
var d = new Date();

Page 10
JAVASCRIPT Notes
var time = [Link]();

if (time < 10)


{
[Link]("Good morning!");
}
else
{
[Link]("Good day!");
}
</script>

If...else if...else Statement

You should use the if....else if...else statement if you want to select one of many sets of lines to execute.

Syntax

if (condition1)
{
code to be executed if condition1 is true
}
else if ( condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and
condition2 are not true
}

Example
<script type="text/javascript">
var d = new Date()
var time = [Link]()
if (time<10)
{
[Link]("<b>Good morning</b>");
}
else if (time>10 && time<16)
{
[Link]("<b>Good day</b>");
}
else

Page 11
JAVASCRIPT Notes
{
[Link]("<b>Hello World!</b>");
}
</script>

The JavaScript Switch Statement


You should use the switch statement if you want to select one of many blocks of code to be executed.
Syntax

switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is
different from case 1 and 2
}

This is how it works: First we have a single expression n (most often a variable), that is evaluated once.
The value of the expression is then compared with the values for each case in the structure. If there is a
match, the block of code associated with that case is executed. Use break to prevent the code from
running into the next case automatically.
Example

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.
var d=new Date();
theDay=[Link]();
switch (theDay)
{
case 5:
[Link]("Finally Friday");
break;
case 6:
[Link]("Super Saturday");
break;
case 0:
[Link]("Sleepy Sunday");

Page 12
JAVASCRIPT Notes
break;
default:
[Link]("I'm looking forward to this weekend!");
}
</script>

JavaScript Controlling(Looping) Statements

Loops in JavaScript are used to execute the same block of code a specified number of times or while
a specified condition is true.
JavaScript Loops

Very often when you write code, you want the same block of code to run over and over again in a row.

Instead of adding several almost equal lines in a script we can use loops to perform a task like this.

In JavaScript there are two different kind of loops:

for - loops through a block of code a specified number of times


while - loops through a block of code while a specified condition is true
The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax

for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}
Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long
as i is less than, or equal to 10. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any comparing statement.

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{

Page 13
JAVASCRIPT Notes
[Link]("The number is " + i);
[Link]("<br />");
}
</script>
</body>
</html>

Result

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

JavaScript While Loop

Loops in JavaScript are used to execute the same block of code a specified number of times or while

a specified condition is true.

The while loop


The while loop is used when you want the loop to execute and continue executing while the specified
condition is true.

while (var<=endvalue)
{
code to be executed
}

Note: The <= could be any comparing statement.


Example

Explanation: The example below defines a loop that starts with i=0. The loop will continue to run as long

as i is less than, or equal to 10. i will increase by 1 each time the loop runs.

<html>

Page 14
JAVASCRIPT Notes
<body>
<script type="text/javascript">
var i=0;
while (i<=10)
{
[Link]("The number is " + i);
[Link]("<br />");
i=i+1;
}
</script>
</body>
</html>

Result

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

The do...while Loop


The do...while loop is a variant of the while loop. This loop will always execute a block of code ONCE,

and then it will repeat the loop as long as the specified condition is true. This loop will always be
executed at least once, even if the condition is false, because the code is executed before the condition is
tested.

do
{
code to be executed
}
while (var<=endvalue);
Example

<html>
<body>
<script type="text/javascript">

Page 15
JAVASCRIPT Notes
var i=0;
do
{
[Link]("The number is " + i);
[Link]("<br />");
i=i+1;
}
while (i<0);
</script>
</body>
</html>

Result

The number is 0

JavaScript Break and Continue

There are two special statements that can be used inside loops: break and continue.
JavaScript break and continue Statements

There are two special statements that can be used inside loops: break and continue.

Break

The break command will break the loop and continue executing the code that follows after the loop (if

any).
Example
<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=10;i++)
{
if (i==3)
{
break;
}
[Link]("The number is " + i);
[Link]("<br />");
}
</script>
</body>

Page 16
JAVASCRIPT Notes
</html>

Result

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

Continue
The continue command will break the current loop and continue with the next value.

Example

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3)
{
continue;
}
[Link]("The number is " + i);
[Link]("<br />");
}
</script>
</body>
</html>
Result

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
The number is 10

Page 17
JAVASCRIPT Notes

JavaScript Functions

A function (also known as a method) is a self-contained piece of code that performs a particular
"function". You can recognise a function by its format - it's a piece of descriptive text, followed by open
and close brackets.A function is a reusable code-block that will be executed by an event, or when the
function is called.
To keep the browser from executing a script when the page loads, you can put your script into a function.

A function contains code that will be executed by an event or by a call to that function.

You may call a function from anywhere within the page (or even from other pages if the function is
embedded in an external .js file).
Functions can be defined both in the <head> and in the <body> section of a document. However, to

assure that the function is read/loaded by the browser before it is called, it could be wise to put it in the
<head> section.
Example

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>
<body>
<form>
<input type="button" value="Click me!"
onclick="displaymessage()" >
</form>
</body>
</html>

If the line: alert("Hello world!!") in the example above had not been put within a function, it would have
been executed as soon as the line was loaded. Now, the script is not executed before the user hits the
button. We have added an onClick event to the button that will execute the function displaymessage()
when the button is clicked.

Page 18
JAVASCRIPT Notes
You will learn more about JavaScript events in the JS Events chapter.
How to Define a Function

The syntax for creating a function is:

function functionname(var1,var2,...,varX)
{
some code
}

var1, var2, etc are variables or values passed into the function. The { and the } defines the start and end of
the function.
Note: A function with no parameters must include the parentheses () after the function name:

function functionname()
{
some code
}

Note: Do not forget about the importance of capitals in JavaScript! The word function must be written in
lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a function with the
exact same capitals as in the function name.
The return Statement

The return statement is used to specify the value that is returned from the function.

So, functions that are going to return a value must use the return statement.

Example
The function below should return the product of two numbers (a and b):

function prod(a,b)
{
x=a*b;
return x;
}

When you call the function above, you must pass along two parameters:

product=prod(2,3);

Page 19
JAVASCRIPT Notes
The returned value from the prod() function is 6, and it will be stored in the variable called product.
The Lifetime of JavaScript Variables

When you declare a variable within a function, the variable can only be accessed within that function.

When you exit the function, the variable is destroyed. These variables are called local variables. You can
have local variables with the same name in different functions, because each is recognized only by the
function in which it is declared.
If you declare a variable outside a function, all the functions on your page can access it. The lifetime of

these variables starts when they are declared, and ends when the page is closed.

JavaScript Arrays

An array object is used to create a database-like structure within a script. Grouping data points
(array elements) together makes it easier to access and use the data in a script. There are methods
of accessing actual databases (which are beyond the scope of this series) but here we're talking
about small amounts of data.
An array can be viewed like a

column of data in a spreadsheet. The


name of the array would be the same
as the name of the column. Each
piece of data (element) in the array
is referred to by a number (index),
just like a row number in a column.
An array is an object. Earlier, I said

that an object is a thing, a collection


of properties (array elements, in this
case) grouped together.
You can name an array using the

same format as a variable, a function or an object. Remember our basic rules: The first
character cannot be a number, you cannot use a reserved word, and you cannot use spaces.
Also, be sure to remember that the name of the array object is capitalized, e.g. Array.
The JavaScript interpreter uses numbers to access the collection of elements (i.e. the data) in

an array. Each index number (as it is the number of the data in the array's index) refers to a
specific piece of data in the array, similar to an ID number. It's important to remember that
the index numbering of the data starts at "0." So, if you have 8 elements, the first element
will be numbered "0" and the last one will be "7."
Elements can be of any type: character string, integer, Boolean, or even another array. An

array can even have different types of elements within the same array. Each element in the

Page 20
JavaScript and DOM Manipulation
array is accessed by placing its index number in brackets, i.e. myCar[4]. This would mean
that we are looking for data located in the array myCar which has an index of "4." Since the
numbering of an index starts at "0," this would actually be the fifth index. For instance, in the
following array,
var myCar = new Array("Chev","Ford","Buick","Lincoln","Truck");

alert(myCar[4])
the data point with an index of "4" would be Truck. In this example, the indexes are

numbered as follows: 0=Chev, 1=Ford, 2=Buick, 3=Lincoln, and 4=Truck. When creating
loops, it's much easier to refer to a number than to the actual data itself.
The Size of the Array

The size of an array is determined by either the actual number of elements it contains or by
actually specifying a given size. You don't need to specify the size of the array. Sometimes,
though, you may want to pre-set the size, e.g.:
var myCar = new Array(20);

That would pre-size the array with 20 elements. You might pre-size the array in order to set

aside the space in memory.

Page 21
JavaScript and DOM Manipulation

Math Object
The Math object allows you to perform mathematical tasks.
The Math object includes several mathematical constants and methods.

Syntax for using properties/methods of Math:

var pi_value=[Link];
var sqrt_value=[Link](16);

Note: Math is not a constructor. All properties and methods of Math can be called by using Math as an
object without creating it.
Mathematical Constants

JavaScript provides eight mathematical constants that can be accessed from the Math object. These are: E,
PI, square root of 2, square root of 1/2, natural log of 2, natural log of 10, base-2 log of E, and base-10 log
of E.
You may reference these constants from your JavaScript like this:

Math.E
[Link]
Math.SQRT2
Math.SQRT1_2
Math.LN2
Math.LN10
Math.LOG2E
Math.LOG10E

Mathematical Methods

In addition to the mathematical constants that can be accessed from the Math object there are also several
methods available.
The following example uses the round() method of the Math object to round a number to the nearest

integer:

[Link]([Link](4.7));

The code above will result in the following output:

Page 22
JavaScript and DOM Manipulation
The following example uses the random() method of the Math object to return a random number between
0 and 1:

[Link]([Link]());

The code above can result in the following output:

0.4218824567728053

The following example uses the floor() and random() methods of the Math object to return a random
number between 0 and 10:

[Link]([Link]([Link]()*11));

The code above can result in the following output:

JavaScript String Object

String object
The String object is used to manipulate a stored piece of text.

Examples of use:

The following example uses the length property of the String object to find the length of a string:

var txt="Hello world!";


[Link]([Link]);

The code above will result in the following output:

12

The following example uses the toUpperCase() method of the String object to convert a string to
uppercase letters:

var txt="Hello world!";


[Link]([Link]());

The code above will result in the following output:

HELLO WORLD!

Page 23
JavaScript and DOM Manipulation

String methods Commonly used:


Strings are fundamental data types in JavaScript, representing sequences of characters. JavaScript provides a
variety of methods to manipulate and work with strings. In this guide, we’ll explore some common string
methods along with coding examples.

length: The length property returns the number of characters in a string.

const greeting = “Hello, World!”;

const length = [Link]; // 13

charAt(index): The charAt() method returns the character at a specified index in the string.

const str = “JavaScript”;

const char = [Link](2); // “v”

substring(start, end): The substring() method extracts a portion of a string between two specified indices.

const text = “Hello, World!”;

const result = [Link](0, 5); // “Hello”

slice(start, end): The slice() method is similar to substring() but allows negative indices to count from the end
of the string.

const phrase = “I love JavaScript!”;

const sliced = [Link](2, -3); // “love JavaScript”

split(separator): The split() method divides a string into an array of substrings based on a specified separator.

const fruits = “apple,banana,cherry”;

const fruitArray = [Link](“,”); // [“apple”, “banana”, “cherry”]

indexOf(searchValue): The indexOf() method returns the index of the first occurrence of a specified value
within the string.

const sentence = “JavaScript is awesome!”;

const index = [Link](“awesome”); // 13

Page 24
JavaScript and DOM Manipulation
replace(searchValue, newValue): The replace() method replaces the first occurrence of a specified value with
another value.

const message = “Hello, John!”;

const newMessage = [Link](“John”, “Alice”); // “Hello, Alice!”

toUpperCase() and toLowerCase(): These methods change the case of characters in a string.

const mixedCase = “ThIs Is MiXeD CaSe”;

const upperCase = [Link](); // “THIS IS MIXED CASE”

trim(): The trim() method removes whitespace from both ends of a string.

const padded = ” Hello, World! “;

const trimmed = [Link](); // “Hello, World!”

concat(): The concat() method combines two or more strings into a new string.

const firstName = “John”;

const lastName = “Doe”;

const fullName = [Link](” “, lastName); // “John Doe”

Page 25
JavaScript and DOM Manipulation

DOM (Document Object Model):

The DOM (Document Object Model) is a programming interface that represents the structure of a web page
in a way that programming languages like JavaScript can understand and manipulate.

Think of it as a tree of objects where each part of your HTML document (elements, attributes, text) is
represented as a node, allowing you to dynamically change or interact with the content and structure of the
page.

What Does the HTML DOM Look Like?

Imagine your webpage as a tree

The document is the root.

HTML tags like <html>, <head>, and <body> are branches.

Attributes, text, and other elements are the leaves.

Page 26
JavaScript and DOM Manipulation

Why is DOM Required?

The DOM is essential because

Dynamic Content Updates: Without reloading the page, the DOM allows content updates (e.g., form
validation, AJAX responses).

User Interaction: It makes your webpage interactive (e.g., responding to button clicks, form submissions).

Flexibility: Developers can add, modify, or remove elements and styles in real-time.

Cross-Platform Compatibility: It provides a standard way for scripts to interact with web documents,
ensuring browser compatibility.

How the DOM Works?

The DOM connects your webpage to JavaScript, allowing you to:

Access elements (like finding an <h1> tag).

Modify content (like changing the text of a <p> tag).

React to events (like a button click).

Create or remove elements dynamically.

Document Object Methods:


Method Description
close() Closes an output stream opened with the
[Link]() method, and displays the
collected data
getElementById() Returns a reference to the first object with the
specified id
getElementsByName() Returns a collection of objects with the specified
name
getElementsByTagName() Returns a collection of objects with the specified
tagname
open() Opens a stream to collect the output from any
[Link]() or [Link]() methods
write() Writes HTML expressions or JavaScript code to a
document
writeln() Identical to the write() method, with the addition
of writing a new line character after each
expression

Page 27
JavaScript and DOM Manipulation

What is an Event?

Event Handlers
Event Handlers are JavaScript methods, i.e. functions of objects, that allow us as JavaScript

programmers to control what happens when events occur.

Directly or indirectly, an Event is always the result of something a user does. For example, we've already
seen Event Handlers like onClick and onMouseOver that respond to mouse actions. Another type of
Event, an internal change-of-state to the page (completion of loading or leaving the page). An onLoad
Event can be considered an indirect result of a user action.
Although we often refer to Events and Event Handlers interchangeably, it's important to keep in mind the

distinction between them. An Event is merely something that happens - something that it is initiated by
an Event Handler (onClick, onMouseOver, etc...).
The elements on a page which can trigger events are known as "targets" or "target elements," and we can

easily understand how a button which triggers a Click event is a target element for this event. Typically,
events are defined through the use of Event Handlers, which are bits of script that tell the browser what to
do when a particular event occurs at a particular target. These Event Handlers are commonly written as
attributes of the target element's HTML tag.

The Event Handler for a Click event at a form field button element is quite simple to understand:
<INPUT TYPE="button" NAME="click1" VALUE="Click me for fun!"

onClick="event_handler_code">
The event_handler_code portion of this example is any valid JavaScript and it will be executed when the

specified event is triggered at this target element. This particular topic will be continued in Incorporating
JavaScripts into your HTML pages.
There are "three different ways" that Event Handlers can be used to trigger Events or Functions.

Method 1 (Link Events)

Places an Event Handler as an attribute within an <A HREF= > tag, like this:
<A HREF="[Link]" onMouseOver="doSomething()">
... </A>
You can use an Event Handler located within an <A HREF= > tag to make either an image or a text link

respond to a mouseover Event. Just enclose the image or text string between the <A HREF= > and the
</A> tags.
Whenever a user clicks on a link, or moves her cursor over one, JavaScript is sent a Link Event. One

Page 28
JavaScript and DOM Manipulation
Link Event is called onClick, and it gets sent whenever someone clicks on a link. Another link event is
called onMouseOver. This one gets sent when someone moves the cursor over the link.
You can use these events to affect what the user sees on a page. Here's an example of how to use link

events. Try it out, View Source, and we'll go over it.


<A HREF="javascript:void('')"

onClick="open('[Link]', 'links', 'height=200,width=200');">How to Use Link Events


</A>
The first interesting thing is that there are no <SCRIPT> tags. That's because anything that appears in the

quotes of an onClick or an onMouseOver is automatically interpreted as JavaScript. In fact, because


semicolons mark the end of statements allowing you to write entire JavaScripts in one line, you can fit an
entire JavaScript program between the quotes of an onClick. It'd be ugly, but you could do it.
Here are the three lines of interest:

1. <A HREF="#" onClick="alert('Ooo, do it again!');">Click on me!</A>


2. <A HREF="javascript:void('')" onClick="alert('Ooo, do it again!');">
Click on me!
</A>
3. <A HREF="javascript:alert('Ooo, do it again!')" >Click on me!</A>
In the first example we have a normal <A> tag, but it has the magic onClick="" element, which says,

"When someone clicks on this link, run the little bit of JavaScript between my quotes." Notice, there's
even a terminating semicolon at the end of the alert. Question: is this required? NO.
Let's go over each line:

1. HREF="#" tells the browser to look for the anchor #, but there is no anchor "#", so the browser
reloads the page and goes to top of the page since it couldn't find the anchor.
2. <A HREF="javascript:void('')" tells the browser not to go anywhere - it "deadens" the link when
you click on it. HREF="javascript: is the way to call a function when a link (hyperlink or an
HREFed image) is clicked.
3. HREF="javascript:alert('Ooo, do it again!')" here we kill two birds with one stone. The default
behavior of a hyperlink is to click on it. By clicking on the link we call the window Method alert()
and also at the same time "deaden" the link.

Page 29
JavaScript and DOM Manipulation
The next line is
<A HREF="javascript:void('')" onMouseOver="alert('Hee hee!');">

Mouse over me!


</A>
This is just like the first line, but it uses an onMouseOver instead of an onClick.

Method 2 (Actions within FORMs):

The second technique we've seen for triggering a Function in response to a mouse action is to place an
onClick Event Handler inside a button type form element, like this:
<FORM>

<INPUT TYPE="button" onClick="doSomething()">


</FORM>
While any JavaScript statement, methods, or functions can appear inside the quotation marks of an Event

Handler, typically, the JavaScript script that makes up the Event Handler is actually a call to a function
defined in the header of the document or a single JavaScript command. Essentially, though, anything that
appears inside a command block (inside curly braces {}) can appear between the quotation marks.
For instance, if you have a form with a text field and want to call the function checkField() whenever the

value of the text field changes, you can define your text field as follows:
<INPUT TYPE="text" onChange="checkField(this)">

Nonetheless, the entire code for the function could appear in quotation marks rather than a function call:
<INPUT TYPE="text" onChange="if ([Link] <= 5) {

alert("Please enter a number greater than 5");


}">
To separate multiple commands in an Event Handler, use semicolons

<INPUT TYPE="text" onChange="alert(‘Thanks for the entry.’);

confirm(‘Do you want to continue?’);">


The advantage of using functions as Event Handlers, however, is that you can use the same Event Handler

code for multiple items in your document and, functions make your code easier to read and understand.
Method 3 (BODY onLoad & onUnLoad):

The third technique is to us an Event Handler to ensure that all required objects are defined involve the
onLoad and onUnLoad. These Event Handlers are defined in the <BODY> or <FRAMESET> tag of an
HTML file and are invoked when the document or frameset are fully loaded or unloaded. If you set a flag

Page 30
JavaScript and DOM Manipulation
within the onLoad Event Handler, other Event Handlers can test this flags to see if they can safely run,
with the knowledge that the document is fully loaded and all objects are defined. For example:
<SCRIPT>

var loaded = false;

function doit() {
// alert("Everything is \"loaded\" and loaded = " + loaded);
alert('Everything is "loaded" and loaded = ' + loaded);
}
</SCRIPT>

<BODY onLoad="loaded = true;">

-- OR --
<BODY onLoad="[Link] = true;">
<FORM>

<INPUT TYPE="button" VALUE="Press Me"


onClick="if (loaded == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if ([Link] == true) doit();">
-- OR --
<INPUT TYPE="button" VALUE="Press Me"
onClick="if (loaded) doit();">
</FORM>
</BODY>

The onLoad Event Handler is executed when the document or frameset is fully loaded, which means that

all images have been downloaded and displayed, all subframes have loaded, any Java Applets and Plugins
(Navigator) have started running, and so on. The onUnLoad Event Handler is executed just before the
page is unloaded, which occurs when the browser is about to move on to a new page. Be aware that when
you are working with multiple frames, there is no guarantee of the order in which the onLoad Event
Handler is invoked for the various frames, except that the Event Handlers for the parent frame is invoked
after the Event Handlers of all its children frames -- This will be discussed in detail in Week 8.
Setting the bgColor Property

The first example allows the user to change the color by clicking buttons, while the second example

allows you to change colors by using drop down boxes.

Page 31
JavaScript and DOM Manipulation
Event Handlers

EVENT DESCRIPTION

onAbort the user cancels loading of an image

input focus is removed from a form element (when the user clicks outside the field) or
onBlur focus is removed from a window

onClick the user clicks on a link or form element

onChange the value of a form field is changed by the user

onError an error happens during loading of a document or image

onFocus input focus is given to a form element or a window

onLoad once a page is loaded, NOT while loading

onMouseOut the user moves the pointer off of a link or clickable area of an image map

onMouseOver the user moves the pointer over a hypertext link

onReset the user clears a form using the Reset button

onSelect the user selects a form element’s field

onSubmit a form is submitted (ie, when the users clicks on a submit button)

onUnload the user leaves a page

Page 32
JavaScript and DOM Manipulation

Note: Input focus refers to the act of clicking on or in a form element or field. This can be done by
clicking in a text field or by tabbing between text fields.
Which Event Handlers Can Be Used

OBJECT EVENT HANDLERS AVAILABLE


Button element onClick, onMouseOver
Checkbox onClick
Clickable ImageMap area onClick, onMouseOver, onMouseOut

Document onLoad, onUnload, onError


Form onSubmit, onReset
Framesets onBlur, onFocus
Hypertext link onClick, onMouseOver, onMouseOut

Radio button onClick


Reset button onClick
Selection list onBlur, onChange, onFocus
Submit button onClick
TextArea element onBlur, onChange, onFocus, onSelect
Text element onBlur, onChange, onFocus, onSelect
Window onLoad, onUnload, onBlur, onFocus

Image onLoad, onError, onAbort

Page 33
JavaScript and DOM Manipulation

• It is important to validate the form submitted by the user because it can have inappropriate
Form Validation:
values. So, validation is must to authenticate user.
• JavaScript provides facility to validate the form on the client-side so data processing will
be faster than server-side validation.
• Most of the web developers prefer JavaScript form validation.
• Through JavaScript, we can validate name, password, email, date, mobile numbers and
more fields.
In this example, we are going to validate the name and password. The name can’t be empty
and password can’t be less than 6 characters long.
Here, we are validating the form on form submit. The user will not be forwarded to the next page
until given values are correct.

<script>
function validateform(){
var name=[Link];
var password=[Link];
if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if([Link]<6){
alert("Password must be at least 6 characters long.");
return false;
}
} </script>

<body>
<form name="myform" method="post" action="[Link]" onSubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>

[Link]
<html>
<head>
<title>Valid User </title>
</head>
<body>
<h1>You are valid user</h1>
<p>Thanks for visiting our site</p>
</body>
</html>

Page 34
JavaScript and DOM Manipulation

Asynchronous JavaScript (callbacks, promises, async/await):


JavaScript provides three main ways to manage asynchronous tasks:

Callbacks: The traditional approach using functions passed as arguments.


Promises: A better alternative that improves readability and avoids callback nesting.
Async/Await: A modern and cleaner syntax that makes asynchronous code look synchronous.

Callbacks:
Callbacks are functions passed as arguments to other functions and are executed once a specific task is
completed.

-Callbacks are passed as arguments to other functions.


-They execute once the asynchronous operation is completed.
-Callback hell can occur with multiple nested callbacks, making the code harder to read and maintain.

// Callback function to process user data


function process(data, callback) {
[Link]("Processing user data:", data);
callback();
}

// Function to fetch user data with a callback


function fetch(callback) {
// Simulating an API request
const user = { id: 1, name: "Pushkar" };
callback(user);
}

// Using the callback


fetch((data) => {
process(data, () => {
[Link]("User data processed successfully.");
});
});

Callbacks are suitable for simple asynchronous operations where you only need to handle one or two
asynchronous tasks. They are the original way to handle asynchronous code in JavaScript.

Page 35
JavaScript and DOM Manipulation

Promises:
Promises offer a more structured approach to handle asynchronous operations, addressing the callback hell
problem. They represent the eventual completion (or failure) of an asynchronous task.

-Promises represent the completion of an asynchronous task.


-They are chained with .then() for successful completion and .catch() for errors.
-Promises improve readability compared to callbacks, preventing nested structures.

// Function to fetch user data with a Promise


function fetch() {
// Simulating an API request
const user = { id: 1, name: "Pushkar" };

return new Promise((resolve, reject) => {


if (user) {
resolve(user);
} else {
reject("Error fetching user data.");
}
});
}

// Using the Promise


fetch()
.then((data) => {
[Link]("Processing user data:", data);
[Link]("User data processed successfully.");
})
.catch((error) => {
[Link]("Error:", error);
});

Promises are a better choice for managing more complex asynchronous code, especially when you have
multiple operations that depend on each other.

Page 36
JavaScript and DOM Manipulation
Async/Await:
Async/Await is built on top of Promises and allows asynchronous code to be written in a synchronous style,
making it easier to read and understand.

// Function to fetch user data with Async/Await


async function fetch() {
// Simulating an API request
const user = { id: 1, name: "Pushkar" };

return new Promise((resolve) => {


resolve(user);
});
}

// Function to process user data using Async/Await


async function process() {
try {
const data = await fetch();
[Link]("Processing user data:", data);
[Link]("User data processed successfully.");
} catch (error) {
[Link]("Error:", error);
}
}

// Using Async/Await
process();

async/await is generally the preferred way to work with asynchronous code in modern JavaScript. It makes
asynchronous code look and behave a bit more like synchronous code.

Page 37
JavaScript and DOM Manipulation

AJAX and the Fetch API:


Both AJAX and the Fetch API are techniques used in web development to make asynchronous HTTP requests
to servers without reloading the entire webpage. This allows web applications to update content dynamically,
improving user experience by making web pages faster and more responsive.

AJAX uses the older XMLHttpRequest object


Fetch API is a modern, promise-based method for making HTTP requests.

AJAX (Asynchronous JavaScript and XML) is a technique that allows web pages to communicate with a server
asynchronously without refreshing the whole page. It traditionally uses the XMLHttpRequest (XHR) object to
send and receive data, often in XML or JSON format.

The Fetch API is a modern, promise-based JavaScript interface for making HTTP requests. It simplifies the
process of fetching resources asynchronously and provides a more powerful and flexible feature set compared
to AJAX.

Ajax Fetch API

Uses the older XMLHttpRequest object for Uses the modern fetch() function based on
requests. Promises.

Relies on callback functions to handle


Uses Promises and async/await.
responses.

Requires manual parsing of response data Provides convenient methods like .json(), .text(),
(e.g., responseText, responseXML). .blob() to parse responses automatically.

Supports progress events for monitoring Does not natively support progress events
upload/download. (requires additional APIs).

More verbose and can lead to "callback hell" Cleaner and more readable syntax, especially
in complex scenarios. with async/await.

Fully supported in all browsers, including very Supported in modern browsers; not supported in
old versions. Internet Explorer without polyfills.

Page 38
JavaScript and DOM Manipulation

jQuery:
jQuery is a fast, small, and feature-rich JavaScript library designed to simplify client-side scripting of HTML. It
simplifies the process of handling events, performing animations, and manipulating HTML documents. jQuery
provides a set of easy-to-use methods and utilities that abstract many complex tasks, making JavaScript coding
more efficient and less cumbersome.

Advantages of jQuery
Simplicity: jQuery simplifies JavaScript coding by providing easy-to-use methods and utilities.
Cross-browser Compatibility: jQuery abstracts browser differences, making it easier to write code that works
consistently across different browsers.
Large Ecosystem: jQuery has a large ecosystem of plugins and extensions that extend its functionality and
provide additional features.
Performance: jQuery is optimized for performance, with efficient DOM manipulation and event handling.

Page 39

You might also like