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

WDT Unit3 JavaScript

JavaScript is a widely-used programming language that serves as the default scripting language for HTML, enabling dynamic web pages through DHTML. It allows for client-side validations, manipulation of HTML elements via the DOM, and supports various programming constructs such as variables, loops, and operators. Additionally, JavaScript provides built-in objects like Date and Math for handling date/time and mathematical operations respectively.

Uploaded by

anil kasula
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 views27 pages

WDT Unit3 JavaScript

JavaScript is a widely-used programming language that serves as the default scripting language for HTML, enabling dynamic web pages through DHTML. It allows for client-side validations, manipulation of HTML elements via the DOM, and supports various programming constructs such as variables, loops, and operators. Additionally, JavaScript provides built-in objects like Date and Math for handling date/time and mathematical operations respectively.

Uploaded by

anil kasula
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

Java Script

Introduction: JavaScript is the world's most popular programming language. JavaScript is the default
scripting language in HTML. It is the programming language of the Web. JavaScript is easy to learn.
By using JavaScript we can perform client side validations. The combination of HTML, CSS, and
JavaScript is called DHTML which gives dynamic nature to a web page.

With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
When a web page is loaded, the browser creates a Document Object Model of the page.

The HTML DOM model is constructed as a tree of Objects

DHTML: DHTML allows authors to add effects to their pages that are otherwise difficult to achieve,
by changing the Document Object Model (DOM) and page style.
The combination of HTML, CSS, and JavaScript offers ways to:

 Animate text and images in their document.


 Embed a ticker or other dynamic display that automatically refreshes its content with the latest
news, stock quotes, or other data.
 Use a form to capture user input, and then process, verify and respond to that data without having
to send data back to the server.
 Include rollover buttons or drop-down menus.

JavaScript Basics: In HTML, JavaScript code is inserted between <script> and </script> tags.
">. Old JavaScript examples may use a type attribute: <script type="text/javascript
The type attribute is not required. JavaScript is the default scripting language in HTML.
We can place any number of scripts in an HTML document.
Scripts can be placed in the <body>, or in the <head> section of an HTML page, or in both.
JavaScript in <head>: In the following code we write myFunction () as part of JavaScript code
placed in head section of html. The function is invoked (called) when a button is clicked:

When we click on Try it button code from the script executes


JavaScript in <body>: In this example, a JavaScript function is placed in the <body> section of an
HTML page.

The function is invoked (called) when a button is clicked:

External JavaScript: External scripts are practical when the same code is used in many different web
pages. JavaScript files have the file extension .js.
To use an external script, put the name of the script file in the src (source) attribute of a <script>
External JavaScript Advantages: Placing scripts in external files has some advantages:
 It separates HTML and code
 It makes HTML and JavaScript easier to read and maintain
 Cached JavaScript files can speed up page loads
To add several script files to one page - use several script tags:

External References: An external script can be referenced in 3 different ways:


 With a full URL (a full web address)
 With a file path (like /js/)
 Without any path
This example uses a full URL to link to [Link]:
<script src="url/ [Link]"></script>
This example uses a file path to link to [Link]:
<script src="/js/[Link]"></script>
This example uses no path to link to [Link]:
<script src="[Link]"></script>
Displaying the output: JavaScript can "display" data in different ways:
1. Writing into the HTML output using [Link]().
2. Writing into an HTML element, using innerHTML.
3. Writing into an alert box, using [Link]().
4. Writing into the browser console, using [Link]().
Using [Link](): For testing purposes, it is convenient to use [Link]():

innerHTML: To access an HTML element, JavaScript can use


the [Link](id) method.

The id attribute defines the HTML element. The innerHTML property defines the HTML content:

[Link]() : You can use an alert box to display data:


<!DOCTYPE html>
<html>
<body>
<h1>My First Web Page</h1>
<p>My first paragraph.</p>
<script>
[Link](5 + 6);
</script>
</body>
</html>

[Link]() : For debugging purposes, we use [Link]() method in the browser to display data.
Variables: In a programming language, v
ariables are used to store data values. JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.

Comments: Comments will improve the readability and understand ability of a program.
Single Line Comments: Single line comments start with //. Any text between // and the end of the line
will be ignored by JavaScript (will not be executed).
Multi-line Comments: Multi-line comments start with /* and end with */.

Any text between /* and */ will be ignored by JavaScript.

Keywords: JavaScript statements often start with a keyword to identify the JavaScript action to be
performed. A keyword is a reserved word which has fixed meaning
Ex: var, let, const, if, switch, for, function , return , try etc.
Identifiers: All JavaScript variables must be identified with unique names. These unique names are
called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, sum,
totalVolume).
JavaScript Primitives : A primitive value is a value that has no properties or methods.3.14 is a
primitive value .A primitive data type is data that has a primitive value. JavaScript defines 7 types of
primitive data types:
Examples:

1. string
2. number
3. boolean
4. null
5. undefined
6. symbol
7. bigint
Immutable: Primitive Values are immutable.
The if Statement: Use the if statement to specify a block of JavaScript code to be executed if a
condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}

The if-else Statement : Use the else statement to specify a block of code to be executed if the
condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Ex:
The else if Statement : Use the else if statement to specify a new condition if the first condition is
false.
Syntax
if (condition1) { // block of code to be executed if condition1 is true
}
else if (condition2) { // block of code to be executed if the condition1
is false and condition2 is true }
else { // block of code to be executed if the condition1 is false and
condition2 is false }

switch statement: Use the switch statement to select one of many code blocks to be executed.
Syntax:
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

The switch expression is evaluated once. The value of the expression is compared with the values of each
case. If there is a match, the associated block of code is executed. If there is no match, the default code
block is executed.

Loops:

For Loop: The for statement creates a loop with 3 optional expressions:
for (expression 1; expression 2; expression 3) {
// code block to be executed
}
Expression 1 is executed (one time) before the execution of the code block.
Expression 2 defines the condition for executing the code block.
Expression 3 is executed (every time) after the code block has been executed.
While loop: The while loop loops through a block of code as long as a specified condition is true.

Syntax
while (condition) {
// code block to be executed
}

The do while: The do while loop is a variant of the while loop. This loop will execute the code block
once, before checking if the condition is true, then it will repeat the loop as long as the condition is true.

Syntax
do {
// code block to be executed
}
while (condition);
Types of JavaScript Operators: an operator is a symbol used to carryout arithmetic or logical
operation

There are different types of JavaScript operators:


1. Arithmetic Operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
6. Conditional Operators
7. Special Operators
1. Arithmetic Operators: Arithmetic Operators are used to perform arithmetic on numbers
Operator Description

+ Addition

- Subtraction

* Multiplication

** Exponent

/ Division

% Modulus (Division Remainder)

++ Increment

-- Decrement

Ex:

2. Assignment Operators: Assignment operators assign values to JavaScript variables


3. Comparison Operators Comparison operators are used in logical statements to determine equality
or difference between variables or values.

Operator Description

== equal to

=== equal value and equal type

!= not equal

!== not equal value or not equal type

> greater than

< less than

>= greater than or equal to

<= less than or equal to

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

Operator Description

&& logical and

|| logical or

! logical not

5. Bitwise Operator: Bit operators work on 32 bits numbers, any numeric operand in the operation
is converted into a 32 bit number. The result is converted back to a JavaScript number.

Operator Description Example Same as Result Decimal

& AND 5&1 0101 & 0001 0001 1

| OR 5|1 0101 | 0001 0101 5

~ NOT ~5 ~0101 1010 10

^ XOR 5^1 0101 ^ 0001 0100 4

<< left shift 5 << 1 0101 << 1 1010 10

>> right shift 5 >> 1 0101 >> 1 0010 2

>>> unsigned right shift 5 >>> 1 0101 >>> 1 0010 2


6. Conditional Operators: JavaScript also contains a conditional operator that assigns a value to a
variable based on some condition.
Syntax:
variablename = (condition) ? value1:value2 ;

7. Special Operators: The following operators are known as JavaScript special operators.

Operator Description

, Comma Operator allows multiple expressions to be evaluated as single


statement.

delete Delete Operator deletes a property from the object.

in In Operator checks if object has the given property

instanceof checks if the object is an instance of given type

new creates an instance (object)

typeof checks the type of object.

void it discards the expression's return value.

yield checks what is returned in a generator by the generator's iterator.


JavaScript array: is an object that represents a collection of similar type of elements.
Creating array
Syntax:
const array_name = [item1, item2, ...];

Ex: const cars = ["Innova", "Audi", "BMW"];

An array can hold many values under a single name, and we can access the values by
referring to an index number.
Creating array by Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

const cars = new Array("Innova", "Audi", "BMW");

Accessing Array Elements: With JavaScript, the full array can be accessed by referring to the array
name:

The length Property: The length property of an array returns the length of an array (the number of
array elements).

Accessing array elements using for loop:


String: The JavaScript string is an object that represents a sequence of characters.

There are 2 ways to create string in JavaScript


1. By string literal
2. By string object (using new keyword)
1. By string literal: The string literal is created using double quotes or single quotes. The syntax of
creating string using string literal is given below:
Ex:
let carName1 = "Volvo XC60"; // Double quotes
let carName2 = 'Volvo XC60'; // Single quotes

2. By string object (using new keyword): strings can also be defined as objects with the
keyword new:
Ex:
let y = new String("John");

Methods Description

charAt() It provides the char value present at the specified index.

concat() It provides a combination of two or more strings.

indexOf() It provides the position of a char value present in the given string.

lastIndexOf() It provides the position of a char value present in the given string by searching a
character from the last position.

search() It searches a specified regular expression in a given string and returns its position
if a match occurs.

replace() It replaces a given string with the specified replacement.

substring() It is used to fetch the part of the given string on the basis of the specified index.

slice() It is used to fetch the part of the given string. It allows us to assign positive as
well negative index.

toLowerCase() It converts the given string into lowercase letter.

toUpperCase() It converts the given string into uppercase letter.

toString() It provides a string representing the particular object.

split() It splits a string into substring array, then returns that newly created array.

trim() It trims the white space from the left and right side of the string.
JavaScript Date and Time Functions: The JavaScript date object can be used to get year, month and
day. You can display a timer on the webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to get and set day,
month, year, hour, minute and seconds.
Constructor:
You can use 4 variant of Date constructor to create date object.
1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)

JavaScript Date Methods

Let's see the list of JavaScript date methods with their description.

Methods Description

getDate() It returns the integer value between 1 and 31 that represents the day for the
specified date on the basis of local time.

getDay() It returns the integer value between 0 and 6 that represents the day of the
week on the basis of local time.

getMinutes() It returns the integer value between 0 and 59 that represents the minutes on
the basis of local time.

getMonth() It returns the integer value between 0 and 11 that represents the month on
the basis of local time.

getSeconds() It returns the integer value between 0 and 60 that represents the seconds on
the basis of local time.

setDate() It sets the day value for the specified date on the basis of local time.

setDay() It sets the particular day of the week on the basis of local time.

setFullYears() It sets the year value for the specified date on the basis of local time.

setHours() It sets the hour value for the specified date on the basis of local time.

setMilliseconds() It sets the millisecond value for the specified date on the basis of local time.

setMinutes() It sets the minute value for the specified date on the basis of local time.

setMonth() It sets the month value for the specified date on the basis of local time.

setSeconds() It sets the second value for the specified date on the basis of local time.

toString() It returns the date in the form of string.

valueOf() It returns the primitive value of a Date object.


JavaScript Math

The JavaScript math object provides several constants and methods to perform mathematical
operation. Unlike date object, it doesn't have constructors.

JavaScript Math Methods

Let's see the list of JavaScript Math methods with description.

Methods Description

ceil() It returns a smallest integer value, greater than or equal to the given number.

floor() It returns largest integer value, lower than or equal to the given number.

hypot() It returns square root of sum of the squares of given numbers.

log() It returns natural logarithm of a number.

max() It returns maximum value of the given numbers.

min() It returns minimum value of the given numbers.

pow() It returns value of base to the power of exponent.

random() It returns random number between 0 (inclusive) and 1 (exclusive).

round() It returns closest integer value of the given number.

sign() It returns the sign of the given number

sin() It returns the sine of the given number.

sinh() It returns the hyperbolic sine of the given number.

sqrt() It returns the square root of the given number

tan() It returns the tangent of the given number.

cos() It returns the cosine of the given number.

cosh() It returns the hyperbolic cosine of the given number.

exp() It returns the exponential form of the given number.


JavaScript Functions: A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses (). The parentheses may include parameter names separated by commas: (parameter1,
parameter2, ...).
The code to be executed, by the function, is placed inside curly brackets: {}

function functionName(parameters) {
// code to be executed
}

Function Return Statement: When JavaScript reaches a return statement, the function will stop
executing. If the function was invoked from a statement, JavaScript will "return" to execute the code
after the invoking statement.

Functions often compute a return value. The return value is "returned" back to the "caller":

A JavaScript function is executed when we invoke it (calls it).


Objects in JavaScript: In JavaScript, almost "everything" is an object. All JavaScript values, except
primitives, are objects. Objects are mutable: They are addressed by reference, not by value.
With JavaScript, you can define and create your own objects.
There are different ways to create new objects:
 Create a single object, using an object literal.
 Create a single object, with the keyword new.
 Define an object constructor, and then create objects of the constructed type.
 Create an object using [Link]().

Objects: JavaScript objects are variables which contain many values. Object values are written
as name : value pairs
Object Definition: we can define (and create) a JavaScript object with an object literal
const person = {firstName:"Ravi",lastName:"K",age:35,eyeColor:"blue"};

Accessing Object Properties: we can access object properties in two ways:


[Link]
or
objectName["propertyName"]
JavaScript Regular Expressions: A regular expression is a sequence of characters that forms a search
pattern. The search pattern can be used for text search and text replace operations. A regular expression
can be a single character, or a more complicated pattern. Regular expressions can be used to perform
all types of text search and text replace operations
Syntax: /pattern/modifiers;
Example: /college/ i;
college is a pattern (to be used in a search). i is a modifier (modifies the search to be case-insensitive).

Object Methods: RegExp Object Methods


exec() It searches a string for a specified pattern, and returns the found text as an object
test() It searches a string for a pattern, and returns true or false, depending on the result.

String Methods: In JavaScript, regular expressions are often used with string object
methods: search() and replace().
search() This method uses an expression to search for a match, and returns the position of the
match
replace() This method returns a modified string where the pattern is replaced
match() Searches for a specified value in a string . Returns array of found values

Regular Expression Modifiers:


g Performs Global match (finds all the matches)
i Performs case insensitive matching
m Performs multiline matching

Brackets: Brackets are used to find a range of characters:

Expression Description

[abc] Find any character between the brackets

[^abc] Find any character NOT between the brackets

[0-9] Find any character between the brackets (any digit)

[^0-9] Find any character NOT between the brackets (any non-digit)

(x|y) Find any of the alternatives specified

Quantifiers define quantities:

Quantifier Description

n+ Matches any string that contains at least one n

n* Matches any string that contains zero or more occurrences of n

n? Matches any string that contains zero or one occurrences of n


Exception Handling:
The try statement defines a code block to run (to try).
The catch statement defines a code block to handle any error.
The finally statement defines a code block to run regardless of the result.
The throw statement defines a custom error.
The JavaScript statements try and catch come in pairs:

The throw statement allows you to create a custom error.


Technically you can throw an exception (throw an error).
The exception can be a JavaScript String, a Number, a Boolean or an Object:

Here c is undefined variable. Now try blocks is throwing an error which is handled by the catch block
.the object err has the error message to be displayed. Finally block executes irrespective of other
statements whether they execute or not.
The Error Object: JavaScript has a built in error object that provides error information when an
error occurs. The error object provides two useful properties: name and message.
Error Object Properties: name , message are the properties
Error Name Values Six different values can be returned by the error name property:
1. Eval error 2. Range Error 3. Reference Error 4. Syntax Error 5. Type Error [Link] Error
DHTML: DHTML allows authors to add effects to their pages that are otherwise difficult to achieve,
by changing the Document Object Model (DOM) and page style.
The combination of HTML, CSS, and JavaScript offers ways to:

 Animate text and images in their document.


 Embed a ticker or other dynamic display that automatically refreshes its content with the latest
news, stock quotes, or other data.
 Use a form to capture user input, and then process, verify and respond to that data without having
to send data back to the server.
 Include rollover buttons or drop-down menus.

Data Validation:
Data validation is the process of ensuring that user input is clean, correct, and useful.
Typical validation tasks are:
 To check for whether the user filled in all required fields?
 To check for whether the user entered a valid date?
 To check for whether the user entered text in a numeric field?
Most often, the purpose of data validation is to ensure correct user input.
Validation can be defined by many different methods, and deployed in many different ways.

Server side validation is performed by a web server, after input has been sent to the server.

Client side validation is performed by a web browser, before input is sent to a web server.

Form Validations in Java script: We can perform form validations using java script . we can
restrict the user must enter the data into a form text field by using the required attribute

Ex: Username: <input id="username" type="text" name="username" required/>

Java script code to restrict the password length at least 8 characters.

if([Link] < 8){


[Link]("Password must be at least 8 charaters")
}

Constraint Validation HTML Input Attributes

Attribute Description

disabled Specifies that the input element should be disabled

max Specifies the maximum value of an input element

min Specifies the minimum value of an input element

pattern Specifies the value pattern of an input element

required Specifies that the input field requires an element

type Specifies the type of an input element


<!DOCTYPE html>
<head>
<title>Form Validation</title>
</head>
<body>
<h1>Login</h1>

<form action="/" method="GET">

Username:
<input id="username" type="text" name="username"
required/> <br>

Password:
<input id="password" type="password" name="password"
required/> <br>

<p id="errorMessage" hidden></p>


<input type="submit" value="SUBMIT"/>
</form>

<script>
username = [Link]("username");
password = [Link]("password");
form = [Link]("form");
errorMessage =
[Link]("errorMessage");

[Link]("submit", (e) => {


const errors = [];

if([Link]() === ""){


[Link]("Username required")
}

if([Link] < 8){


[Link]("Password must be at least 8
charaters")
}

if([Link] > 0){


[Link]();
[Link]('hidden');
[Link] = [Link](', ');
}
})
</script>
</body>
</html>
Java Script is event driven system: Java script is an event driven system. HTML events
are "things" that happen to HTML elements.

When JavaScript is used in HTML pages, JavaScript can "react" on these events.
JavaScript lets us execute code when events are detected. HTML allows event handler attributes, with
JavaScript code, to be added to HTML elements.

HTML Events: An HTML event can be something the browser does, or something a user does.
Here are some examples of HTML events:
 An HTML web page has finished loading
 An HTML input field was changed
 An HTML button was clicked
Synatx:
<element event='some JavaScript'>

With double quotes:


<element event="some JavaScript">

In the above example we are clicking on button which is event we write event handler code in java
script
Common HTML Events

Here is a list of some common HTML events:

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page


Opening a new Window:

JavaScript offers in-built methods to open and close the browser window to perform additional
operations like robot window etc. These methods help to open or close the browser window pop-ups.
Following are the window methods:

o open()
o close()

The [Link] method is used to open a new web page into a new window
and [Link] method to close web page opened by [Link] method. See the [Link]()
method in detail:

Syntax
[Link](URL, name, specs, replace)

URL – Optional parameter. The URL of the page to open. If no URL is specified, a new blank
window/tab is opened

Name- Optional. The target attribute or the name of the window. The following values are supported,
_blank, _self ,_top etc

Specs- Optional. A comma-separated list of items, no whitespaces.


The following values are supported: full screen , height, width etc .

Replace – deprecated / no longer in use


Messages and Confirmations:
JavaScript provides built-in global functions to display popup message boxes for different purposes.
 alert(message): Display a popup box with the specified message with the OK button.

<!DOCTYPE html>
<html>
<head>
<script>
alert("alert messsage");
</script>
</body>
</html>

 confirm(message): Display a popup box with the specified message with OK and Cancel
buttons.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Confirmations</h2>
<script>
confirm("confirmtion message.");
</script>
</body>
</html>

 prompt(message, defaultValue): Display a popup box to take the user's input with the OK and
Cancel buttons.
<!DOCTYPE html>
<html>
<body>
<h1>Demo: prompt()</h1>
<button onclick="myinput()">Click to enter your
name</button>
<p id="msg"></p>
<script>
function myinput(){
var name = prompt("Enter Your Name:");
}
</script>
</body>
</html>
Status bar: Status bar is part of the website . The Window status property in HTML DOM is used
to set or return the text in the status bar at the bottom of the browser.
Syntax:
[Link]
Note: This property has been DEPRECATED and is no longer recommended.
<!DOCTYPE html>
<html>
<head>
<title>
HTML DOM Window status Property
</title>
</head>
<body>
<!-- Script to use window status property -->
<script>
[Link] = "status bar";
[Link] = "status bar";
</script>
</body>
</html>

Frames: The following example explains how to use frames in a web page. We are creating three html
files [Link] has frames where we add [Link] and [Link] as part of this [Link]

<html> <html> <html>


<head> <head> <head>
<title>Frames</title> <title> <title>
</head> Page one Page one
</title> </title>
<frameset cols="50%,*" > <script>
<frame src = "[Link]"> function a(){ </head>
<frame src = "[Link]"> <body>
</frameset> [Link]("Hello");
</html> } <script>
</script> function hello(){
</head> [Link]("Hello");
<body> }
<h1> Frame1</h1> </script>
</body> <form>
</html> <input type="button" value="hello"
onClick="hello()">
[Link] [Link] </form>
</body>

</html>
Moving Images: we can move/slide an image from left to right . We create an HTML page and insert
an image and button in the page when a click a button Move the Image From Left to Right Javascript
with a 10px value. This is a simple javascript code that allows shifting the image by some particular
pixel in this case we are shifting an image by 10px

<!DOCTYPE html>
<head>
<title>JavaScript Animation</title>
<script type="text/javascript">

var imgObj = null;


function init(){
imgObj = [Link]('myImage');
[Link]= 'relative';
[Link] = '0px';
}
function moveRight(){
[Link] = parseInt([Link]) + 10 + 'px';
}
[Link] =init;

</script>
</head>
<body>
<form>
<img id="myImage" src="[Link]" height="400" width="600" />
<p>Click button below to move the image to right</p>
<input type="button" value="Click Me" onclick="moveRight();" />
</form>
</body>

</html>
Rollover Buttons: in this technique we use two images. When mouse is moved the images will be
swapped. A image is displayed on a web page, when we move mouse over it another image will be
displayed. We can write java script functions with onMouseOver and onMouseOut events

<!doctype html>
<html>

<head>
<meta charset="utf-8">
<title>How to Make a JavaScript Image
Rollover</title>

<!--JavaScript code goes here.-->


<script language="javascript">
function MouseRollover(MyImage)
{
[Link] = "[Link]";
}
function MouseOut(MyImage) {
[Link] = "[Link]";
}
</script>
</head>

<body>

<div align="center">

<!--The rollover image displays here.-->


<img src="[Link]" boarder="0px"
width="650px" height="550px"
onMouseOver="MouseRollover(this)"
onMouseOut="MouseOut(this)" />
</div>

</body>
</html>

You might also like