0% found this document useful (0 votes)
38 views162 pages

Unit IV, Javascript Basics

This document provides an overview of JavaScript, including its definition as a scripting language, its features, advantages, limitations, and syntax. It explains the capabilities of JavaScript in web development, such as creating dynamic web pages, handling events, and interacting with APIs, while also outlining what JavaScript cannot do. Additionally, it covers JavaScript data types, variable declarations, scopes, reserved words, and various operators.

Uploaded by

zuckonitmeta
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)
38 views162 pages

Unit IV, Javascript Basics

This document provides an overview of JavaScript, including its definition as a scripting language, its features, advantages, limitations, and syntax. It explains the capabilities of JavaScript in web development, such as creating dynamic web pages, handling events, and interacting with APIs, while also outlining what JavaScript cannot do. Additionally, it covers JavaScript data types, variable declarations, scopes, reserved words, and various operators.

Uploaded by

zuckonitmeta
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

Unit Iv

Javascript Basics
Prepared by
Binayak Maharjan
Introduction to Scripting Language
Introduction to scripting language
● A scripting language is a programming language designed for integrating and
communicating with other programming languages.
● A scripting language is a programming language used to automate tasks, control
other software, or create dynamic content in applications or websites.
● Some of the most widely used scripting languages are JavaScript, VBScript, PHP,
Perl, Python, Ruby, ASP, and Tcl.
● Uses:
○ Web Development: JavaScript for client-side interactivity, PHP for
server-side processing.
○ Task Automation: Python or Bash for system tasks.
○ Game Development: Lua in gaming engines.
Client side vs server side scripting language
Introduction to 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 is very easy to implement because it is integrated with HTML.
● It is open and cross platform.
● JavaScript made its first appearance in Netscape 2.0 in 1995 with the name
LiveScript.
Features of javascript
● Lightweight and Interpreted: JavaScript is executed directly in the browser
without the need for compilation.
● Client-Side Scripting: Runs in the user’s browser to create interactive and
dynamic web pages.
● Event-Driven Programming: Handles events like clicks, hovers, and form
submissions efficiently.
● Dynamic Typing: Variables can hold different data types, and types are
determined at runtime.
● Object-Oriented: Supports objects, prototypes, and inheritance for building
reusable code.
Features of javascript
● DOM Manipulation: Allows direct interaction with HTML and CSS to update
web content dynamically.
● Extensive Libraries and Frameworks :Includes powerful frameworks like
React, Angular, and [Link] for web development.
● Integration with Other Technologies: Works seamlessly with HTML, CSS, and
server-side languages like PHP or [Link].
● Platform Independence: Runs on any browser or environment with a
JavaScript engine (e.g., [Link]).
Advantages of javascript
● Executes on the client-side, reducing server load.
● Easy to learn with simple syntax.
● Runs quickly as it's interpreted directly in the browser.
● Enables dynamic and interactive web content.
● Compatible with all major browsers and platforms.
● Offers a rich ecosystem of libraries and frameworks.
● Versatile for both client-side and server-side programming.
● Allows real-time DOM manipulation for dynamic pages.
● Efficiently handles events like clicks and inputs.
Limitations of javascript
● Behavior can vary across browsers, requiring compatibility checks.
● Vulnerable to security issues like XSS if not managed well.
● Cannot directly access the local file system for security reasons.
● Limited to single-threaded execution, affecting heavy computations.
● Debugging errors in large-scale projects can be challenging.
● Relies on browser settings, which may disable JavaScript.
● Loose typing can lead to unexpected behavior.
● Performance may degrade with poorly optimized scripts.
What javascript can do and cannot?
What javascript can do?
● Create Dynamic Web Pages: Modify HTML and CSS in real-time using the DOM.
● Event Handling: Respond to user actions like clicks, keypresses, and mouse
movements.
● Form Validation: Validate input fields on the client-side before sending data to the
server.
● Interact with APIs: Fetch and manipulate data from servers or third-party services
using AJAX or Fetch API.
● Animation and Graphics: Create animations using libraries (e.g., GSAP) or HTML5
Canvas for 2D/3D graphics.
● Browser Storage: Store data locally using LocalStorage, SessionStorage, or Cookies.
● Server-Side Programming: Build backends with frameworks like [Link].
● Cross-Platform Applications: Develop desktop and mobile apps using frameworks
like Electron and React Native.
What javascript cannot do?
● Access Local Files Directly: Cannot read or write files on a user's system without user
input or APIs (e.g., FileReader).
● System-Level Operations: Cannot access hardware, install software, or perform
low-level system tasks.
● Threading and Multitasking: Operates in a single-threaded environment, with limited
support for multi-threading via Web Workers.
● Secure Content Access: Cannot bypass browser security measures to access restricted
domains or data.
● Native OS Features: Cannot directly access features like camera, GPS, or notifications
without APIs or permissions.
● Guaranteed Execution: If JavaScript is disabled in the user's browser, it won't execute.
● Complex Mathematical Computations: Handles intensive computations less efficiently
compared to low-level languages like C++.
Javascript syntax
● JavaScript can be implemented using JavaScript statements that are placed within the
<script>... </script> HTML tags in a web page.
● Scripts can be in the either <head> section or <body> section but it is normally
recommended to keep it within the <head> tags.
● Syntax:
<script language=”javascript” type="text/javascript">

…..
</script>
● The script tag takes two important attributes:
○ Language: This attribute specifies what scripting language you are using. Typically,
its value will be javascript. Although recent versions of HTML (and XHTML, its
successor) have phased out the use of this attribute.
○ Type: This attribute is what is now recommended to indicate the scripting language
in use and its value should be set to "text/javascript".
Javascript example
<!DOCTYPE html>
<html>
<body>
<script language="javascript" type="text/javascript">
[Link] ("Hello World!")
</script>
</body>
</html>

Note: [Link] is a standard JavaScript command for writing output to a page. By


entering the [Link]() command between the <script> & </script> tag, the browser will
recognize it as a javascript command and execute the code line.
Things to remember
● JavaScript supports both C-style and C++-style comments.
● JavaScript is a case-sensitive language.
● JavaScript are generally followed by a semicolon character but not compulsory:
<script language="JavaScript" type="text/JavaScript">
var1 = 10
var2 = 20
</script>
● But when formatted in a single line as follows, you must use semicolons:
<script language="JavaScript" type="text/JavaScript">
var1 = 10; var2 = 20;
</script>
● Note: It is a good programming practice to use semicolons.
Using Javascript in HTML document
Javascript implementations
● JavaScript code can be embedded in:
○ Internal
○ An external file
● Internal: JavaScript can be embedded internally in any head and body section. It can be
use in both section like:
<html>
<head>
<script type="text/javascript" >
function sayHello() {
alert("Hello World" )
}
</script>
</head>
<body>
<script type="text/javascript" >
[Link]("Hello World" )
</script>
<input type="button" onclick="sayHello()" value="Say Hello" />
</body>
</html>
Javascript implementations
● External file: same as in CSS
<script type="text/javascript" src="[Link]" ></script>
● Example:
In [Link]
<html>
<head>
<script type="text/javascript" src="[Link]">
</script>
</head>
</html>

In [Link]
[Link](“This is external implementation”)
Javascript fundamentals
● External file: same as in CSS
<script type="text/javascript" src="[Link]" ></script>
● Example:
In [Link]
<html>
<head>
<script type="text/javascript" src="[Link]">
</script>
</head>
</html>

In [Link]
[Link](“This is external implementation”)
Programming fundamentals
Javascript data types
● JavaScript allows us to work with three primitive data types:
● Numbers, eg. 123, 120.50, etc.
● Strings of text e.g. "This text string" etc.
● Boolean e.g. true or false.
● JavaScript also defines two trivial data types, null and undefined, each of which
defines only a single value.
● JavaScript supports a composite data type known as an object.
Javascript Variables
● Variables are Containers for Storing Data
● JavaScript Variables can be declared in 4 ways:
a. Automatically
b. Using var
c. Using let
d. Using const
● Example:
<script>
var price1 = 5;
const price2 = 6;
let total = price1 + price2;
[Link]("demo").innerHTML =
"The total is: " + total;
</script>
Javascript Variables
● There are some rules while declaring a JavaScript variable (also known as
identifiers).
○ Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ )
[Link] first letter we can use digits (0 to 9), for example: “value1”,
”_value123”.
○ We should not use any of the JavaScript reserved keywords as a variable
name. These keywords are mentioned in the next section. For example,
break or boolean variable names are not valid.
○ JavaScript variables are case sensitive, for example Name and name are
two different variables.
Javascript Variable scope
● The scope of a variable is the region of our program in which it is defined.
JavaScript variables have only two scopes.
1. Global Variables: A global variable has global scope which means it can be
defined anywhere in our JavaScript code.

2. Local Variables: A local variable will be visible only within a function


where it is defined. Function parameters are always local to that function.
Javascript Variable scope
● Example:
<html>
<body onload = checkscope();>
<script type = "text/javascript">
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
[Link](myVar);
}
</script>
</body>
</html>
Javascript Reserved words
A list of all the reserved words in JavaScript are given in the following table. They cannot be
used as JavaScript variables, functions, methods, loop labels, or any object names.
abstract class enum function long

boolean const export goto native

break continue extends if new

byte debugger false implements null

case default final import package

catch class finally instanceof private

char do float int protected

delete else for interface Public

return short static typeof Var

void while super switch this

volatile with in synchronized Throw

throws transient true try double


Javascript operators
arithmetic Operators
S.N. Operator Description

1 + (Addition) Adds two operands Ex: A=10 + B=20 will give 30

- (Subtraction) Subtracts the second operand from the first Ex: A - B will give
2
-10

3 * (Multiplication) Multiply both operands Ex: A * B will give 200

/ (Division)
4 Divide the numerator by the denominator Ex: B / A will give 2

% (Modulus)
5 Outputs the remainder of an integer division Ex: B % A will give 0

++ (Increment)
6 Increases an integer value by one Ex: A++ will give 11

7 -- (Decrement) Decreases an integer value by one Ex: A-- 10 will give 9

Note: Addition operator (+) works for Numeric as well as Strings. e.g. "a" + 10 will give "a10".
Comparison Operators
[Link]. Operator Description

1 = = (Equal) Checks if the value of two operands are equal or not, if yes, then the condition becomes true.
Ex: (A == B) is not true.

2 != (Not Equal) Checks if the value of two operands are equal or not, if the values are not equal, then the condition becomes
true.
Ex: (A != B) is true.

3 > (Greater than) Checks if the value of the left operand is greater than the value of the right the operand, if yes, then the
condition becomes true.
Ex: (A > B) is not true.

4 < (Less than) Checks if the value of the left operand is less than the value of the right operand, if yes, then the condition
becomes true.
Ex: (A < B) is true.

5 >= (Greater than or Equal Checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then
to) the condition becomes true.
Ex: (A >= B) is not true.

6 <= (Less than or Equal to) Checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the
condition becomes true.
Ex: (A <= B) is true.
logical Operators
[Link]. Operator Description

1 && (Logical AND) If both the operands are non-zero, then the condition becomes
true. Ex: (A && B) is true.
2 || (Logical OR) If any of the two operands are non-zero, then the condition becomes
true. Ex: (A || B) is true.
3 ! (Logical NOT) Reverses the logical state of its operand. If a condition is true, then the
Logical NOT operator will make it false.
Ex: ! (A && B) is false.
Bitwise Operators
[Link]. Operator
Description
1 & (Bitwise AND)
It performs a Boolean AND operation on each bit of its integer arguments. Ex: (A & B) is 2.

2 | (BitWise OR)
It performs a Boolean OR operation on each bit of its integer arguments. Ex: (A | B) is 3.

3 ^ (Bitwise XOR) It performs a Boolean exclusive OR operation on each bit of its integer arguments. Exclusive OR
means that either operand one is true or operand two is true, but not both.
Ex: (A ^ B) is 1.
4 ~ (Bitwise Not)
It is a unary operator and operates by reversing all the bits in the operand. Ex: (~B) is -4.

5 << (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the second
operand. New bits are filled with zeros. Shifting a value left by one position is equivalent to
multiplying it by 2, shifting two positions are equivalent to multiplying by 4, and so on.
Ex: (A << 1) is 4.
6 >> (Right Shift) Binary Right, Shift Operator. The left operand’s value is moved right by the number of bits specified
by the right operand.
Ex: (A >> 1) is 1.
7 >>> (Right shift with Zero)
This operator is just like the >> operator, except that the bits shifted in on the left are always zero.
Ex: (A >>> 1) is 1.
Assignment Operators
[Link]. Operator
Description

1 = (Simple Assignment Assigns values from the right side operand to the left side operand Ex: C = A + B
) will assign the value of A + B into C

2 += (Add and It adds the right operand to the left operand and assigns the result to the left operand.
Assignment) Ex: C += A is equivalent to C = C + A

3 −= (Subtract and It subtracts the right operand from the left operand and assigns the result to the left
Assignment) operand.
Ex: C -= A is equivalent to C = C - A
4 *= (Multiply and It multiplies the right operand with the left operand and assigns the result to the left
Assignment) operand.
Ex: C *= A is equivalent to C = C * A
5 /= (Divide and It divides the left operand with the right operand and assigns the result to the left operand.
Assignment) Ex: C /= A is equivalent to C = C / A

6 %= (Modules and It takes modulus using two operands and assigns the result to the left operand.
Assignment) Ex: C %= A is equivalent to C = C % A
Conditional Operators
[Link]. Operator
Description

1 ? : (Conditional )
If Condition is true? Then value X : Otherwise value Y
typeof Operators
Type String Returned by typeof
● The typeof operator is a unary operator that is
Number "number"
placed before its single operand, which can be of
any type. Its value is a string indicating the data String "string"
type of the operand.
● The typeof operator evaluates to "number", Boolean "boolean"
"string", or "boolean" if its operand is a number,
Object "object"
string, or boolean value and returns true or false
based on the evaluation.
Function "function"
● Here is a list of the return values for the typeof
Operator.:-> Undefined "undefined"

Null "object"
typeof Operators
● Example:
<html>
<body>
<script type="text/javascript">
var a = 10;
var b = "String";
var linebreak = "<br />";
result = (typeof b == "string" ? "B is String" : "B is Numeric");
[Link]("Result => ");
[Link](result);
[Link](linebreak);
result = (typeof a == "string" ? "A is String" : "A is Numeric");
[Link]("Result => ");
[Link](result);
[Link](linebreak);
</script>
</body>
</html>
Javascript conditional statements
Javascript if statement
● It evaluates the content only if expression is true.
● The signature of JavaScript if statement is given below.
if(expression){
//content to be evaluated
}
● Example
<script>
var a=20;
if(a>10){
[Link]("value of a is greater than 10");
}
</script>
Javascript if else statement
● It evaluates the content whether condition is true of false.
● The syntax of JavaScript if-else statement is given below.
if(expression){
//content to be evaluated if condition is true
} else{
//content to be evaluated if condition is false
}
Javascript if else statement
● Example
<script>
var a=20;
if(a%2==0){
[Link]("a is even number");
} else{
[Link]("a is odd number");
}
</script>
Javascript 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.
if(expression1){
//content to be evaluated if expression1 is true
} 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
}
Javascript if else if statement
● Example:
<script>
var a=20;
if(a==10){
[Link]("a is equal to 10");
} else if(a==15){
[Link]("a is equal to 15");
} else if(a==20){
[Link]("a is equal to 20");
} else{
[Link]("a is not equal to 10, 15 or 20");
}
</script>
Javascript switch statement
● The JavaScript switch statement is used to execute one code from multiple
expressions.
● The syntax of JavaScript switch statement is given below.
switch(expression){
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
......
default:
code to be executed if above values are not matched;
}
Javascript switch statement
<script>
var grade='B';
var result;
switch(grade){
case 'A':
result="A Grade";
break;
case 'B':
result="B Grade";
break;
case 'C':
result="C Grade";
break;
default:
result="No Grade";
}
[Link](result);
</script>
Javascript loops
Javascript loops
● 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.
● There are four types of loops in JavaScript.
○ for loop
○ while loop
○ do-while loop
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.
● The syntax of for loop is given below.
for (initialization; condition; increment)
{
code to be executed
}
● Example
<script>
for (i=1; i<=5; i++)
{
[Link](i + "<br/>")
}
</script>
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.
● The syntax of while loop is given below.
while (condition)
{
code to be executed
}
● Example
<script>
var i=11;
while (i<=15) {
[Link](i + "<br/>");
i++; }
</script>
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.
● The syntax of do while loop is given below.
do{
code to be executed
}
while (condition);
● Example
<script>
var i=21;
do{ [Link](i + "<br/>");
i++;
}while (i<=25);
</script>
Jump statements
Break statement
● The break statement, which was briefly introduced with the switch statement, is used to
exit a loop early, breaking out of the enclosing curly braces.
● Example:
<script type="text/javascript">
var x = 1;
[Link]("Entering the loop<br /> ");
while (x < 20) {
if (x == 5){
break; // breaks out of loop completely
}
x = x + 1;
[Link]( x + "<br />");
}
[Link]("Exiting the loop!<br /> ");
</script>
continue statement
● The continue statement tells the interpreter to immediately start the next
iteration of the loop and skip the remaining code block.
● When a continue statement is encountered, the program flow moves to the
loop check expression immediately and if the condition remains true, then it
starts the next iteration, otherwise the control comes out of the loop.
● Example:
<script type="text/javascript">
var x = 1;
[Link]("Entering the loop<br /> ");
while (x < 10)
{
x = x + 1;
if (x == 5){
continue; // skip rest of the loop body }
[Link]( x + "<br />");
}
[Link]("Exiting the loop!<br /> ");
</script>
Dialog/Popup boxes
dialog/popup box
● JavaScript supports three important types of dialog boxes i.e, alert dialog box,
confirmation dialog box and prompt dialog box. These dialog boxes can be
used to raise an alert, or to get confirmation on any input or to have a kind of
input from the users.
Alert dialog box
● An alert box is often used if you want to make sure information comes through
to the user.
● When an alert box pops up, the user will have to click "OK" to proceed.
● Syntax:
alert("sometext");
Alert dialog box
● Example:
<html>
<head>
<script type="text/javascript">
function Warn() {
alert ("This is a warning message!");
[Link] ("This is a warning message!"); }
</script>
</head>
<body>
<p>Click the following button to see the result: </p> <form>
<input type="button" value="Click Me" onclick="Warn();" /> </form>
</body>
</html>
Confirm dialog box
● A confirm box is often used if you want the user to verify or accept something.
● When a confirm box pops up, the user will have to click either "OK" or "Cancel"
to proceed.
● If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box
returns false.
● Syntax:
confirm("sometext");
Confirm dialog box
● Example:
<html>
<head>
<script type="text/javascript">
function getConfirmation(){
var retVal = confirm("Do you want to continue ?"); if( retVal == true ){
[Link] ("User wants to continue!"); return true;
}
else{
[Link] ("User does not want to continue!"); return false;
}
}
</script>
</head>
<body>
<p>Click the following button to see the result: </p> <form>
<input type="button" value="Click Me" onclick="getConfirmation();" />
</form>
</body>
</html>
prompt dialog box
● A prompt box is often used if you want the user to input a value before entering
a page.
● When a prompt box pops up, the user will have to click either "OK" or "Cancel"
to proceed after entering an input value.
● If the user clicks "OK" the box returns the input value. If the user clicks "Cancel"
the box returns null.
● Syntax:
prompt("sometext",”default_text”);
prompt dialog box
● Example:
<html>
<head>
<script type="text/javascript">
function getValue(){
var retVal = prompt("Enter your name : ", "your name here");
[Link]("You have entered : " + retVal); }
</script>
</head>
<body>
<p>Click the following button to see the result: </p> <form>
<input type="button" value="Click Me" onclick="getValue();" />
</form>
</body>
</html>
Javascript function
Javascript function
● A function is a group of reusable code which can be called anywhere in our
program.
● This eliminates the need of writing the same code again and again. It helps
programmers in writing modular codes.
● Functions allow a programmer to divide a big program into a number of small
and manageable functions.
● Like any other advanced programming language, JavaScript also supports all
the features necessary to write modular code using functions.
● JavaScript allows us to write our own functions as well.
Javascript function
● A JavaScript function is defined with the function keyword, followed by a name,
followed by parentheses ( ).
● Function names can contain letters, digits, underscores, and dollar signs (same
rules as variables).
● The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
● The code to be executed, by the function, is placed inside curly brackets: { }
● Syntax :
<script type="text/javascript">
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
</script>
Calling a function
● There is different ways of calling a function. They are:-

○ By using function name: To invoke a function somewhere in the script,


you simply write the name of the function.
○ Syntax:
<script type=“text/javascript”>
function_name()
</script>
Calling a function
● Example:
<html>
<head>
<script type="text/javascript">
function sayHello()
{
[Link] ("Hello there!");
}
</script>
</head>
<body>
<p>Click the following button to call the function</p> <form>
<input type="button" onclick="sayHello()" value="Say Hello">
</form>
<p>Use different text in write method and then try...</p>
</body>
</html>
Calling a function
○ By passing parameters: To invoke a function somewhere in the script,
you simply write the name of the function along with some parameters to
be passed while calling.
○ A function can take multiple parameters separated by a comma.
○ Syntax:
<script type=“text/javascript”>
function_name(parameter 1, parameter 2)
</script>
Calling a function
● Example:
<html>
<head>
<script type="text/javascript" >
function add(a,b){
var c= a+b;
[Link](a”+”b”=”c)
}
</script>
</head>
<body>
<script type="text/javascript" >
add(20,20)
</script>
</body>
</html>
Return statement
● A JavaScript function can have an optional return statement. This is required if
we want to return a value from a function. This statement should be the last
statement in a function.
● Example:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function add(a,b){
var c= a+b;
return c;
}
</script>
</head>
<body>
<script type="text/javascript">
var sum;
sum=add(20,20);
[Link]("Sum is: " ,sum);
</script>
</body>
</html>
Nested function
● We can define function within another function called nested function.
● These nested functions have access to the variables and parameters of the
outer (enclosing) function, creating a scope hierarchy.
● Syntax:
// Outer function
function outerFunction() {
// Nested function
function nestedFunction() {
// Function logic here
}
// Call the nested function
nestedFunction();
// Rest of the outer function logic
}
// Call the outer function
outerFunction();
Nested function
● Example:
<html>
<head>
<script type="text/javascript">
function hypotenuse(a, b) {
function square(x) { return x*x; }
return [Link](square(a) + square(b));
}
function secondFunction(){
var result;
result = hypotenuse(1,2);
[Link] ( result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p> <form>
<input type="button" onclick="secondFunction()" value="Call Function">
</form>
<p>Use different parameters inside the function and then try...</p> </body>
</html>
Calling function with timer
● In JavaScript the timer is a very important feature, it allows us to execute a
JavaScript function after a specified period, thereby making it possible to add a
new dimension, time, to our website.
● With the help of the timer, we can run a command at specified intervals, run
loops repeatedly at a predefined time, and synchronize multiple events in a
particular time span.
● There are various methods for calling function with a timer such as:
○ The setTimeout() method
○ The clearTimeout() method
○ The setInterval() method
○ The clearInterval() method
The setTimeout() method
● Executes code at a specified interval.
● Syntax:
setTimeout(function, delayTime);
● In the preceding syntax, the setTimeout() method contains two parameters, function,
and delayTime.
● The function parameter specifies the method that the timer calls and the delayTime
parameter specify the number of milliseconds to wait before calling the method.
● Example:
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/JavaScript">
function timedMsg(){
var message;
message = setTimeout("alert('This is use of setTimeout
Function')",3000);
}
</script>
</head>
<body>
<form>
<p>Click the button below and output will be seen in 3
Second</p>
<input type = "button" value = "Start" onclick = "timedMsg()"/>
</form>
</body>
</html>
The clearTimeout() method
● Deactivates or cancels the timer that is set using the setTime() method.
● Syntax:
clearTimeout(timer);
● In the preceding syntax, timer is a variable that is created using the setTimeout()
method.
● Example:
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/JavaScript">
var message;
function setMessage(){
message = setTimeout("alert('This is use of setTimeout
Function')",3000);
}
function clearMessage(){
clearTimeout(message);
alert("This is use of clearTimeout Function");
}
</script>
</head>
<body>
<form>
<p>Click the button below and output will be seen in 3 Second</p>
<input type = "button" value = "Start" onclick = "setMessage()"/>
<input type = "button" value = "Stop" onclick = "clearMessage()"/> </form>
</body>
</html>
The setInterval() method
● The setInterval() method repeats a given function at every given time-interval.
● Syntax:
setInterval(function, milliseconds);
● The first parameter is the function to be executed. The second parameter indicates the
length of the time-interval between each execution.
● Example:
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/JavaScript">
function timedMsg(){
var message;
message = setInterval("alert('This is the use of setInterval
Function')",3000);
}
</script>
</head>
<body>
<form>
<p>Click the button below and output will be seen in 3 Second</p>
<input type = "button" value = "Start" onclick = "timedMsg()"/>
</form>
</body>
</html>
The clearInterval() method
● The clearInterval() method stops the executions of the function specified in the
setInterval() method.
● Syntax:
clearInterval(timerVariable);
● Example:
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/JavaScript" >
var message;
function setMessage (){
message = setInterval ("alert('This is use of setInterval
Function')" ,3000);
}
function clearMessage (){
clearInterval (message);
alert("This is use of clearInterval Function" );
}
</script>
</head>
<body>
<form>
<p>Click the button below and output will be seen in 3 Second </p>
<input type = "button" value = "Start" onclick = "setMessage ()"/>
<input type = "button" value = "Stop" onclick = "clearMessage ()"/> </form>
</body>
</html>
Events and event handlers
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
● Often, when events happen, you may want to do something.
● JavaScript lets you execute code when events are detected.
● HTML allows event handler attributes, with JavaScript code, to be added to HTML
elements.
● Syntax:
With single quotes: <element event='some JavaScript'>
With double quotes: <element event="some JavaScript">
Event Handlers
● An event handler in JavaScript is a function or code segment that is executed in
response to an event on an element in the Document Object Model (DOM).
● Events can include user actions (like clicks, key presses, or mouse movements) or
system-generated events (like the page loading or resizing).
● Event handlers can be used to handle and verify user input, user actions, and browser
actions:
● Things that should be done every time a page loads
● Things that should be done when the page is closed
● Action that should be performed when a user clicks a button
● Content that should be verified when a user inputs data
● And more …
Common HTML Events
Onload and onunload Events
● The onload and onunload events are triggered when the user enters or leaves the page.
● The onload event can be used to check the visitor's browser type and browser version,
and load the proper version of the web page based on the information.
● The onload and onunload events can be used to deal with cookies.
● Syntax:

<element onload="functionName( )" onunload="functionName( )">


Onload and onunload Events
● Example:
<html>
<head>
<title>onload and onunload Example</title>
<script>
// Function to be executed when the page loads
function pageLoad() {
alert("Welcome! The page has loaded.");
[Link]("Page has loaded.");
}
</script>
</head>
<body onload="pageLoad()">
<h1>onload Event Handler</h1>
<p>Open the developer console to see the log messages when the page
loads.</p>
</body>
</html>
oninput Events
● The oninput event is often to some action while the user input data.
● Syntax:

<element oninput="functionName( )" >


oninput Events
● Example: W3Schools Tryit Editor
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The oninput Attribute</h2>
Enter your name: <input type="text" id="fname" oninput="upperCase()">
<p>When you write in the input field, a function is triggered to transform
the input to upper case.</p>
<script>
function upperCase() {
const x = [Link]("fname");
[Link] = [Link]();
}
</script>
</body>
</html>
onchange Events
● The onchange event is often used in combination with validation of input fields.
● Syntax:

<element onchange="functionName( )" >


oninput Events
● Example: W3Schools Tryit Editor
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onchange Attribute</h2>
Enter your name: <input type="text" id="fname" onchange="upperCase()">
<p>When you leave the input field, a function transforms the input to upper
case.</p>
<script>
function upperCase() {
const x = [Link]("fname");
[Link] = [Link]();
}
</script>
</body>
</html>
Onmouseover and onmouseout Events
● The onmouseover and onmouseout events can be used to trigger a function when the
user mouses over, or out of, an HTML element.
● Syntax:

<element onmouseover="functionName( )" onmouseout=”functionName( )” >


Onmouseover and onmouseout Events
● Example: W3Schools Tryit Editor
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events</h1>
<h2>The onmouseover Attribute</h2>
<div onmouseover="mOver(this)" onmouseout="mOut(this)"
style="background-color:#D94A38;width:120px;height:20px;padding:40px;">
Mouse Over Me</div>
<script>
function mOver(obj) {
[Link] = "Thank You"
}
function mOut(obj) {
[Link] = "Mouse Over Me"
}
</script>
</body>
</html>
Onmousedown, onmouseup and onclick Events
● The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First
when a mouse-button is clicked, the onmousedown event is triggered, then, when the
mouse-button is released, the onmouseup event is triggered, finally, when the
mouse-click is completed, the onclick event is triggered.
● Syntax:

<element onmousedown="functionName( )" onmouseup=”functionName( )”


onclick=”functionName( )>
Onmouseover and onmouseout Events
● Example: W3Schools Tryit Editor
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript HTML Events </h1>
<h2>The onmousedown Attribute </h2>
<div onmousedown ="mDown(this)" onmouseup ="mUp(this)"
style="background-color:#D94A38;width:90px;height:20px;padding:40px;" >
Click Me</div>
<script>
function mDown(obj) {
[Link] = "#1ec5e5" ;
[Link] = "Release Me" ;
}
function mUp(obj) {
[Link] ="#D94A38" ;
[Link] ="Thank You" ;
}
</script>
</body>
Javascript form validation
● 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.
name and password validation
● The name can’t be empty and password can’t be less than 6 characters long.
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;
}
● Example:
<!DOCTYPE html>
<html>
<body>
<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" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
Password: <input type="password" name="password"><br/>
<input type="submit" value="register">
</form>
</body>
</html>
Javascript number validation
● Let's validate the textfield for numeric value only. Here, we are using isNaN() function.
<!DOCTYPE html>
<html>
<head>
<script>
function validate(){
var num=[Link];
if (isNaN(num)){
[Link]("numloc").innerHTML="Enter Numeric value only";
return false;
}else{
return true;
}
}
</script>
</head>
<body>
<form name="myform" onsubmit="return validate()" >
Number: <input type="text" name="num"><span id="numloc"></span><br/>
<input type="submit" value="submit">
</form>
</body>
</html>
Javascript Email Validation
● We can validate the email by the help of JavaScript.
● There are many criteria that need to be follow to validate the email id such as:
○ email id must contain the @ and . character
○ There must be at least one character before and after the @.
○ There must be at least two characters after . (dot).
● Example:
<html>
<body>
<script>
function validate_email ()
{
var x=[Link];
var atposition =[Link]("@");
var dotposition =[Link] (".");
if (atposition <1 || dotposition <atposition +6 || dotposition +3>=[Link]){
alert("Please enter a valid e-mail address!!" );
return false;
}
}
</script>
<body>
<form name="myform" method="post" onsubmit="return validate_email ();">
Email: <input type="text" name="email"><br/>
<input type="submit" value="register" >
</form>
</body>
</html>
Javascript Arrays
An Array is an object type designed for storing data collections.

Key characteristics of JavaScript arrays are:

● Elements: An array is a list of values, known as elements.


● Ordered: Array elements are ordered based on their index.
● Zero indexed: The first element is at index 0, the second at index 1, and so on.
● Dynamic size: Arrays can grow or shrink as elements are added or removed.
● Heterogeneous: Arrays can store elements of different data types (numbers, strings,
objects and other arrays).
● Using an array literal is the easiest way to create a JavaScript Array.
○ Syntax:

const array_name = [item1, item2, ...];

Note: It is a common practice to declare arrays with the const keyword.


Javascript Arrays
Example:

const cars = ["Saab", "Volvo", "BMW"];

const cars = [

"Saab",

"Volvo",

"BMW"

];

const cars = [];

cars[0]= "Saab";

cars[1]= "Volvo";

cars[2]= "BMW";
Javascript Arrays
Accessing Array Elements

You access an array element by referring to the index number:

const cars = ["Saab", "Volvo", "BMW"];


let car = cars[0];

Changing an Array Element

This statement changes the value of the first element in cars:

const cars = ["Saab", "Volvo", "BMW"];

cars[0] = "Opel";
Javascript Array Methods
pop()
• The pop() method removes the last element from an array:
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();//Output: Mango
push()
• The push() method adds a new element to an array (at the end):
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("Kiwi");
[Link](fruits); \\output: Banana,Orange,Apple,Mango,Kiwi
Javascript Array Methods
shift()
• The shift() method removes the first array element and "shifts" all other elements to a
lower index.
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]();
[Link](fruits); \\Orange,Apple,Mango
• The shift() method returns the value that was "shifted out".
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruit = [Link]();
[Link](fruit); \\output: Banana
Javascript Array Methods
unshift()
• The unshift() method adds a new element to an array (at the beginning), and "unshifts"
older elements.
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link]("Lemon");
[Link](fruits); \\output: Lemon,Banana,Orange,Apple,Mango
• The unshift() method returns the new array length.
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fruitLength = [Link]("Lemon");
[Link](fruitLength); \\output: 5
Javascript Array Methods
delete():
• Using delete() leaves undefined holes in the array.
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
delete fruits[0];
[Link](fruits[0]); \\output: undefined
concat():
• The concat() method creates a new array by merging (concatenating) existing arrays
const myGirls = ["Cecilie", "Lone"];
const myBoys = ["Emil", "Tobias", "Linus"];
const myChildren = [Link](myBoys);
[Link](myChildren) \\Output: Cecilie, Lone, Emil, Tobias, Linus
Javascript Array Methods
splice():
• The splice() method adds new items to an array.
• Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](2, 0, "Lemon", "Kiwi");//output: Banana,Orange,Lemon,Kiwi,Apple,Mango
• The first parameter (2) defines the position where new elements should be added (spliced
in).
• The second parameter (0) defines how many elements should be removed. If the second
parameter was 1, the output would be: Banana,Orange,Lemon,Kiwi,Mango
• The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.
Javascript Array Methods
Using splice() to Remove Elements
• With clever parameter setting, you can use splice() to remove elements without leaving
"holes" in the array
const fruits = ["Banana", "Orange", "Apple", "Mango"];
[Link](0, 1);
[Link](fruits); \\ouput: Orange,Apple,Mango
• The first parameter (0) defines the position where new elements should be added (spliced
in).
• The second parameter (1) defines how many elements should be removed.
• The rest of the parameters are omitted. No new elements will be added.
Javascript Array Methods
• slice():
• The slice() method slices out a piece of an array into a new array:
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = [Link](1);
[Link](citrus); \\ouput: Orange,Lemon,Apple,Mango
• The slice() method can take two arguments like slice(1, 3). The method then selects
elements from the start argument, and up to (but not including) the end argument.
const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
const citrus = [Link](1, 3);
[Link](citrus); \\output: Orange,Lemon
Javascript Object
● An object in JavaScript is a data structure used to store related data collections.
● Objects are variables too. But objects can contain many values.
● It stores data as key-value pairs, where each key is a unique identifier for the associated
value.
● Objects are dynamic, which means the properties can be added, modified, or deleted at
runtime.
● Javascript is an Object Oriented Programming (OOP) language.
● Example:
○ Javascript variable:
let car = "Fiat";
○ Javascript object:
const car = {type:"Fiat", model:"500", color:"white"};
Javascript Object definition
● We can define javascript objects in following three ways:
○ Using Object Literal
○ Using the new keyword
○ Using an Object Constructor Function
Using Object Literal
● An object literal is a list of name:value pairs inside curly braces {}.
{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}

● Example: W3Schools Tryit Editor


<html>
<body>
<h1>Creating JavaScript Objects</h1>
<h2>Using an Object Literal</h2>
<p id="demo"></p>
<script>
// Create an Object:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
// Display Data from the Object:
[Link]("demo").innerHTML =
[Link] + " is " + [Link] + " years old.";
</script>
</body>
</html>
Using the new keyword
● We can create a new JavaScript object using new Object() keyword.
● Example: W3Schools Tryit Editor
<html>
<body>
<h1>Creating JavaScript Objects </h1>
<h2>Using the new Keyword </h2>
<p id="demo"></p>
<script>
// Create an Object
const person = new Object();
[Link] = "John";
[Link] = "Doe";
[Link] = 50;
[Link] = "blue";
// Diplay Object Content
document .getElementById ("demo").innerHTML =
[Link] + " is " + [Link] + " years old." ;
</script>
</body>
</html>
Using the Object Constructor Function
● Sometimes we need to create many objects of the same type. To create an object type we
use an object constructor function.
● Example: W3Schools Tryit Editor
<html>
<body>
<h1>JavaScript Object Constructors </h1>
<p id="demo"></p>
<script>
// Constructor Function for Person objects
function Person(first, last, age, eye) {
[Link] = first;
[Link] = last;
[Link] = age;
[Link] = eye;
}
// Create a Person object
const myFather = new Person("John", "Doe", 50, "blue");
// Display age
document .getElementById ("demo").innerHTML =
"My father is " + myFather .age + ".";
</script>
</body></html>
Javascript Object Properties
● Properties are the most important part of JavaScript objects.
● Properties can be changed, added, deleted, and some are read only.
● To know more about javascript object properties visit:
○ Object methods: JavaScript object methods
○ JavaScript Properties
Javascript Object Methods
● Object methods are actions that can be performed on objects.
● A method is a function definition stored as a property value.
● Commonly used javascript object methods are:

1. [Link](obj)

Returns an array of property names (keys) of an object.

const person = { name: "Ram", age: 20, city: "Kathmandu" };

[Link]([Link](person)); \\output: ["name", "age", "city"]


Javascript Object Methods
2. [Link](obj)

Returns an array of property values.

[Link]([Link](person)); \\Output: ["Ram", 20, "Kathmandu"]

3. [Link](obj)

Returns an array of key–value pairs.

[Link]([Link](person)); \\output: [ ["name", "Ram"], ["age", 20], ["city",


"Kathmandu"] ]
Javascript Object Methods
4. [Link](target, source)

Copies properties from one or more objects to another object.

const obj1 = { a: 1 };

const obj2 = { b: 2 };

const result = [Link](obj1, obj2);

[Link](result);
Javascript Object Methods
5. [Link](obj)

Prevents modification of object properties.

const user = { username: "admin" };

[Link](user);

[Link] = "guest"; // will not change

[Link]([Link]);
Javascript Object Methods
6. [Link](obj)

Allows modification of existing properties but prevents adding or deleting properties.

const car = { brand: "Toyota" };

[Link](car);

[Link] = "Honda"; // allowed

[Link] = "City"; // not allowed


Javascript Object Methods
7. [Link](obj, property)

Checks if the object has a direct property.

[Link]([Link](person, "age")); \\Output: true

8. [Link](property)

Older method to check own property.

[Link]([Link]("city"));
Javascript Object Methods
9. [Link](proto)

Creates a new object using an existing object as a prototype.

const animal = { eats: true };

const dog = [Link](animal);

[Link]([Link]);

10. [Link](obj1, obj2)

Compares two values for strict equality.

[Link]([Link](10, 10));

[Link]([Link](NaN, NaN));
Document object model
● The Document Object Model (DOM) is a cross-platform and language-independent
interface that treats an HTML or XML document as a tree structure wherein each node is
an object representing a part of the document.
● The DOM represents a document with a logical [Link] branch of the tree ends in a
node, and each node contains objects.
● The principal standardization of the DOM was handled by the World Wide Web
Consortium (W3C), which last developed a recommendation in 2004.
● In HTML DOM (Document Object Model), every element is a node:[4]
○ A document is a document node.
○ All HTML elements are element nodes.
○ All HTML attributes are attribute nodes.
○ Text inserted into HTML elements are text nodes.
○ Comments are comment nodes.
Document object model
● DOM has a specific treemap structure like below:
Document object model

simple hierarchy of a few important objects in DOM
simple hierarchy of a few important objects in DOM
○ Window object − Top of the hierarchy. It is the outmost element of the object
hierarchy.
○ Document object − Each HTML document that gets loaded into a window becomes
a document object. The document contains the contents of the page.
○ Form object − Everything enclosed in the <form>...</form> tags sets the form
object.
○ Form control elements − The form object contains all the elements defined for
that object such as text fields, buttons, radio buttons, and checkboxes.
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.
Different DOM methods and Properties
● JavaScript - DOM Methods & Properties
● HTML DOM (Document Object Model) - GeeksforGeeks
Commonly Used DOM Methods and Properties
A. DOM Selection Methods

1. [Link]()

Definition: Selects an element using its id.

Syntax: Output:
Hello changes to Welcome
[Link]("id")

Example:

<p id="msg">Hello</p>
<script>
[Link]("msg").innerText = "Welcome";
</script>
Commonly Used DOM methods and Properties
2. [Link]()

Definition: Selects elements using class name.

Syntax:

[Link]("className")
Output:
First paragraph text becomes
Example: red
<p class="t">One</p>
<p class="t">Two</p>
<script>
[Link]("t")[0].[Link] = "red";
</script>
Commonly Used DOM methods and Properties
3. [Link]()

Definition: Selects elements using tag name.

Syntax:

[Link]("tag")

Example: Output:
Heading text becomes Hi
<h1>Hello</h1>
<script>
[Link]("h1")[0].innerText = "Hi";
</script>
Commonly Used DOM methods and Properties
4. [Link]()

Definition: Selects the first matching element using CSS selector.

Syntax:

[Link]("selector")

Example: Output:
Text becomes bold
<p class="info">Text</p>
<script>
[Link](".info").[Link] = "bold";
</script>
Commonly Used DOM methods and Properties
5. [Link]()

Definition: Selects all matching elements.

Syntax:

[Link]("selector")

Example: Output:
Second paragraph text becomes
<p>A</p><p>B</p>
blue
<script>
[Link]("p")[1].[Link] = "blue";
</script>
Commonly Used DOM methods and Properties
B. DOM Content Properties

1. innerHTML

Definition: Gets or sets HTML inside an element.

Syntax:

[Link] Output:
Text appears bold Hello
Example:

[Link]("msg").innerHTML = "<b>Hello</b>";
Commonly Used DOM methods and Properties
2. innerText

Definition: Gets or sets visible text.

Syntax:

[Link]

Example: Output:
Text changes to World
[Link]("msg").innerText = "World";
Commonly Used DOM methods and Properties
3. textContent

Definition: Gets all text including hidden text.

Syntax:

[Link]

Example:

[Link]([Link]("msg").textContent);

Output (Console):
Displays element text
Commonly Used DOM methods and Properties
C. Style & Class Properties

1. style

Definition: Applies inline CSS styles.

Syntax:

[Link] = "value"

Example:

[Link]("msg").[Link] = "green";
Output:
Text color becomes green
Commonly Used DOM methods and Properties
2. classList

Definition: Adds, removes, or toggles CSS classes.

Syntax:

[Link]("className")

Example:

[Link]("box").[Link]("active");

Output:
Class active is added
Commonly Used DOM methods and Properties
D. Form & Attribute Properties

1. value

Definition: Gets or sets form input value.

Syntax:

[Link]

Example: Output (Console):


Ram
<input id="name" value="Ram">
<script>
[Link]([Link]("name").value);
</script>
Commonly Used DOM methods and Properties
2. setAttribute()

Definition: Sets attribute value.

Syntax:

[Link]("attr", "value")

Example:

[Link]("img").setAttribute("alt", "photo");

Output:
Attribute added
Commonly Used DOM methods and Properties
3. getAttribute()

Definition: Gets attribute value.

Syntax:

[Link]("attr")

Example:

[Link]([Link]("img").getAttribute("alt"));

Output:(console)

photo
Commonly Used DOM methods and Properties
4. removeAttribute()

Definition: Removes attribute.

Syntax:

[Link]("attributename)

Example:

[Link]("btn").removeAttribute("value");

Output:
Button value is removed
Commonly Used DOM methods and Properties
E. Event Handling

1. addEventListener()

Definition: Attaches an event handler.

Syntax:

[Link]("event", function)

Example:

[Link]("click", () => alert("Clicked"));


Output:
Alert box appears on click
Commonly Used DOM methods and Properties
F. DOM Creation & Removal

1. createElement()

Definition: Creates new HTML element.

Syntax:

[Link]("tag")

Example:

const p = [Link]("p");
Output:
[Link] = "New"; Paragraph created (not yet
visible)
Commonly Used DOM methods and Properties
2. appendChild()

Definition: Adds child element.

Syntax:

[Link](child)

Example:

[Link](p);

Output:
Paragraph appears on page
Commonly Used DOM methods and Properties
3. removeChild()

Definition: Removes child from parent.

Syntax:

[Link](child)

Example:

[Link](child);

Output:
Element removed
Commonly Used DOM methods and Properties
3. remove()

Definition: Removes element directly.

Syntax:

[Link]()

Example:

[Link]("msg").remove();

Output:
Element disappears
Commonly Used DOM methods and Properties
G. DOM Navigation Properties

1. parentElement

Definition: Returns parent element.

Syntax:

[Link]

Example:

[Link]([Link]);
Output:
Parent tag name printed
Commonly Used DOM methods and Properties
2. children

Definition: Returns child elements.

Syntax:

[Link]

Example:

[Link]([Link].l

Output:
Number of child elements
Commonly Used DOM methods and Properties
3. nextElementSibling

Definition: Returns next sibling element.

Syntax:

[Link]

Example:

[Link] = "red";

Output:
Next element turns red
Errors and Exception Handler
● Unused condition occur in the program is error.
● Error is also called exception.
● An exception signifies the presence of an abnormal condition which requires special
operable techniques.
● In programming terms, an exception is the anomalous code that breaks the normal flow
of the code. Such exceptions require specialized programming constructs for its
execution.
● In programming, exception handling is a process or method used for handling the
abnormal statements in the code and executing them.
● It also enables to handle the flow control of the code/program.
● For handling the code, various handlers are used that process the exception and execute
the code.
● For example, the Division of a non-zero value with zero will result into infinity always,
and it is an exception. Thus, with the help of exception handling, it can be executed and
handled.
Errors and Exception Handler
● Types of errors:
a. Syntax Error: When a user makes a mistake in the pre-defined syntax of a
programming language, a syntax error may appear.
b. Runtime Error: When an error occurs during the execution of the program, such an
error is known as Runtime error. The codes which create runtime errors are known
as Exceptions. Thus, exception handlers are used for handling runtime errors.
c. Logical Error: An error which occurs when there is any logical mistake in the
program that may not produce the desired output, and may terminate abnormally.
Such an error is known as Logical error.
The Try…Catch statement
● A try…catch is a commonly used statement in various programming languages.
● Basically, it is used to handle the error-prone part of the code.
● It initially tests the code for all possible errors it may contain, then it implements actions
to tackle those errors (if occur).
● A good programming approach is to keep the complex code within the try…catch
statements.
● We can catch programmer-generated and runtime exceptions, but you cannot catch
JavaScript syntax errors.
● Try…..catch has two block
○ Try block🡪 code contain a block of code that is to be tested for error
○ Catch block 🡪 contain the code that is to be executed if an error occur.
The Try…Catch statement
● try{} statement:
○ Here, the code which needs possible error testing is kept within the try block.
○ In case any error occur, it passes to the catch{} block for taking suitable actions and
handle the error.
○ Otherwise, it executes the code written within.

● catch{} statement:
○ This block handles the error of the code by executing the set of statements written
within the block.
○ This block contains either the user-defined exception handler or the built-in
handler.
○ This block executes only when any error-prone code needs to be handled in the try
block.
○ Otherwise, the catch block is skipped.
The Try…Catch Statement
● Syntax:
<script type="text/javascript">
try {
// Code to run
[break;]
}
catch ( e ) {
// Code to run if an exception(e) occurs
[break;]
}
The Try…Catch statement
● Example:
<html>
<head>
<script type="text/javascript" >
function myFunc(){
var a = 100;
try {
dalert("Value of variable a is : " + a );
}
catch ( e ) {
alert("Error: " + [Link] );
}}
</script>
</head>
<body>
<p>Click the following to see the result: </p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
The Throw statement
● A throw statement is used to raise an exception. It means when an abnormal condition
occurs, an exception is thrown using throw.
● The thrown exception is handled by wrapping the code into the try…catch block. If an
error is present, the catch block will execute, else only the try block statements will get
executed.
● Throw statements are used for throwing user-defined errors. User can define and throw
their own custom errors. When throw statement is executed, the statements present
after it will not execute. The control will directly pass to the catch block.
● Syntax:
try{
throw exception; // user can define their own exception
}
catch(error){
expression; } // code for handling exception.
The throw statement
● Example:
<html>
<head>
<script type="text/javascript" >
function myFunc(){
var a = 100;
var b = 0;
try{
if ( b == 0 ){
throw( "Divide by zero error." );
}
else{
var c = a / b;
} }
catch ( e ) {
alert("Error: " + e );
} }
</script>
</head>
<body>
<p>Click the following to see the result: </p>
<form><input type="button" value="Click Me" onclick="myFunc();" /></form>
</body>
</html>
The Onerror() statement
● The Onerror event occur when a page has a script error.
● Onerror event occur when an image or document causes an error during loading.
● This doesn't mean that it is a browser error.
● The error event is fired on the window object whenever an exception occurs on the page.
● Synatx:
onerror=function_name()
function function_name(){
//error handling code
}
● The onerror event handler provides three pieces of information to identify the exact
nature of the error:
○ Error message: The same message that the browser would display for the given
error.
○ URL: The file in which the error occurred
○ Line number: The line number in the given URL that caused the error
The Onerror() statement
● Example:
<html>
<head>
<script type = "text/javascript">
[Link] = function (msg, url, line) {
alert("Message : " + msg );
alert("url : " + url );
alert("Line number : " + line );
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form><input type = "button" value = "Click Me" onclick =
"myFunc();" /></form>
</body>
</html>
Important Questions:
1. Define DOM with hierarchy. Explain different properties and method of DOM with
example.
2. What is event handler? Explain about onclick event, onsubmit event, onmouseover and
onmouseout event.
3. What do you mean by event in javascript? Write a html code to create login form with
three input fields Name , Password and Email and write javascript code that will prevent
from submit and display suitable pop up message if either username or password field is
empty.
4. What is Javascript? Explain Window and String object in Javascript. Explain any five
string object methods with example.
5. Write a javascript code to validate with following conditions:
a. Name field should contain only alphabets
b. Email field should contain @ and .(dot)
c. Password should be at least 8 character long.
6. Define function with its type in javascript.

You might also like