0% found this document useful (0 votes)
126 views

Unit-3 HTML Java Script

The document provides information about JavaScript including: 1. JavaScript is a lightweight scripting language used widely in web pages for dynamic interactivity. It allows dynamic updating of HTML. 2. The document outlines the features of JavaScript including being cross-platform, using C-like syntax, being weakly typed, and using prototypes for inheritance. 3. Examples are given of using JavaScript code in HTML documents, including in <script> tags between the <head> and <body> tags, and in external .js files. Common JavaScript statements and programming constructs are also defined.

Uploaded by

Harsha Vardhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
126 views

Unit-3 HTML Java Script

The document provides information about JavaScript including: 1. JavaScript is a lightweight scripting language used widely in web pages for dynamic interactivity. It allows dynamic updating of HTML. 2. The document outlines the features of JavaScript including being cross-platform, using C-like syntax, being weakly typed, and using prototypes for inheritance. 3. Examples are given of using JavaScript code in HTML documents, including in <script> tags between the <head> and <body> tags, and in external .js files. Common JavaScript statements and programming constructs are also defined.

Uploaded by

Harsha Vardhan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Unit -3

JavaScript
• JavaScript (js) is a light-weight object-oriented interpreted, scripting language
which is used by several websites for scripting the webpages.
• It enables dynamic interactivity on websites when applied to an HTML document.
• JavaScript is an object-based scripting language which is lightweight and cross-
platform.

Features of JavaScript

1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus,
it is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-based scripting language that uses prototypes rather than
using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows,
macOS, etc.
8. It provides good control to the users over the web browsers.

History of JavaScript

• in May 1995, Marc Andreessen coined the first code of Javascript named
'Mocha'.
• Later, the marketing team replaced the name with 'LiveScript'.
• in December 1995, the language was finally renamed to 'JavaScript'. From
then, JavaScript came into existence.

Application of JavaScript

JavaScript is used to create interactive websites. It is mainly used for:

o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm
dialog box and prompt dialog box),
o Displaying clocks etc.

Places to put JavaScript code

1. Between the body tag of html


2. Between the head tag of html
3. In .js file (external javaScript)

1) code between the body tag

In the above example, we have displayed the dynamic content using JavaScript. Let’s see
the simple example of JavaScript that displays alert dialog box.

<html>

<body>

<script type="text/javascript">

alert("Hello Javatpoint");

</script>

</body>

</html>

2) code between the head tag

Let’s see the same example of displaying alert dialog box of JavaScript that is contained
inside the head tag.

In this example, we are creating a function msg(). To create function in JavaScript, you
need to write function with function_name as given below.

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

<head>

<script type="text/javascript">

function msg(){

alert("Hello Javatpoint");

</script>

</head>

<body>

<p>Welcome to Javascript</p>

<form>

<input type="button" value="click" onclick="msg()"/>

</form>

</body>

</html>

3)External JavaScript file

We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in several html
pages.

An external JavaScript file must be saved by .js extension. It is recommended to embed


all JavaScript files into a single file. It increases the speed of the webpage.

Let's create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.
message.js

function msg(){
alert("Hello Javatpoint");
}

Let's include the JavaScript file into html page. It calls the JavaScript function on button
click.

index.html

<html>
<head>
<script type="text/javascript" src="message.js"></script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/> </form> </body> </html>

Javascript Data Types:

JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.

1. Primitive data type


2. Non-primitive (reference) data type

JavaScript is a dynamic type language, means you don't need to specify type of the
variable because it is dynamically used by JavaScript engine. You need to use var here
to specify the data type. It can hold any type of values such as numbers, strings etc.

For example: var a=40;//holding number

var b="Rahul";//holding string

Primitive data types

There are five types of primitive data types in JavaScript. They are as follows:
Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

Null represents null i.e. no value at all

non-primitive data types

The non-primitive data types are as follows:Hello Java Program for Beginners

Data Description
Type

Object represents instance through which we can access


members

Array represents group of similar values

RegExp represents regular expression

JavaScript Variable

A JavaScript variable is simply a name of storage location.

There are two types of variables in JavaScript :

1) local variable
2) global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).
1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.
2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.

Ex: var x = 10;


var _value="sonoo";

<html>

<body>

<script>

var x = 10;

var y = 20;

var z=x+y;

document.write(z);

</script>

</body>

</html>

Statements in JavaScript
JavaScript supports threes types of statements.
1. branching statements
2. looping statements
3. jumping statements

Branching statements:

The conditional branching statements help to jump from one part of the program to another
depending on whether a particular condition is satisfied or not.

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

1.If statement

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


statement is given below.

Syntax: if(expression){

//content to be evaluated
}

Flowchart

Example: <html>

<body>

<script>

var a=20;

if(a>10){

document.write("value of a is greater than 10");

}
</script> </body></html>

Output: value of a is greater than 10

2.If...else Statement

It evaluates the content whether condition is true of false. The syntax of JavaScript if-
else statement is given below.

Syntax: if(expression){
//content to be evaluated if condition is true
}
else{
//content to be evaluated if condition is false
}

Flowchart If...else statement

Ex: <html>

<body><script>

var a=20;

if(a%2==0){

document.write("a is even number");

}
else{

document.write("a is odd number");

</script></body></html>

Output: a is even number

3.If...else if statement:

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

Syntax: if(expression1){
Statement block1;
}
else if(expression2){
Statement block2; }
else if(expression3){
Statement block3; }
else{
Statement block4; }
Example:

<html>

<body>

<script>

var a=20;

if(a==10){

document.write("a is equal to 10");

else if(a==15){

document.write("a is equal to 15");


}

else if(a==20){

document.write("a is equal to 20");

else{

document.write("a is not equal to 10, 15 or 20");

</script> </body></html>

Output: a is equal to 20

4)Switch

The JavaScript switch statement is used to execute one code from multiple expressions.
It is just like else if statement that we have learned in previous page. But it is convenient
than if..else..if because it can be used with numbers, characters etc.

Syntax: switch(expression){
case value1: statement block1;
break;
case value2: statement block1;
break;
......
default:

Example: <!DOCTYPE html>

<html>

<body>

<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";

document.write(result);

</script>

</body>

</html>

Output: B Grade
Looping statements:

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

There are four types of loops in JavaScript.

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

1.For loop

The JavaScript for loop iterates the elements for the fixed number of times. It should be
used if number of iteration is known. The syntax of for loop is given below.

Syntax: for (initialization; condition; increment)


{
code to be executed
}
Example: <!DOCTYPE html>
<html>
<body>
<script>
for (i=1; i<=5; i++)
{
document.write(i + "<br/>")
}
</script> </body></html>
Output:1
2
3
4
5
2) while loop

The JavaScript while loop iterates the elements for the infinite number of times. It
should be used if number of iteration is not known. The syntax of while loop is given
below.

Syntax: while (condition)


{
code to be executed
}
Example: <!DOCTYPE html>
<html>
<body>
<script>
var i=11;
while (i<=15)
{
document.write(i + "<br/>");
i++;
}
</script> </body></html>
Output:
11
12
13
14
15

3) do while loop

The JavaScript do while loop iterates the elements for the infinite number of times like
while loop. But, code is executed at least once whether condition is true or false. The
syntax of do while loop is given below.

Syntax: do{
code to be executed
}while (condition);
Example:
<!DOCTYPE html>
<html>
<body>
<script>
var i=21;
do{
document.write(i + "<br/>");
i++;
}while (i<=25);
</script> </body></html>
Output:21
22
23
24
25

JavaScript Functions
JavaScript functions are used to perform operations. We can call JavaScript function
many times to reuse the code.

Advantage of JavaScript function

There are mainly two advantages of JavaScript functions.

1. Code reusability: We can call a function several times so it save coding.


2. Less coding: It makes our program compact. We don’t need to write many lines
of code each time to perform a common task.

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

//code to be executed
}
JavaScript Functions can have 0 or more arguments.

Example: <html>

<body>

<script>

function msg(){

alert("hello! this is message");

</script>

<input type="button" onclick="msg()" value="call function"/>

</body></html>

Function with Arguments

We can call function by passing arguments. Let’s see the example of function that has
one argument.

<html>

<body>

<script>

function getcube(number){

alert(number*number*number);

</script>

<form>

<input type="button" value="click" onclick="getcube(4)"/>


</form> </body></html>

Function with Return Value

We can call function that returns a value and use it in our program. Let’s see the
example of function that returns value.

<html>

<body>

<script>

function getInfo(){

return "hello javatpoint! How r u?";

</script>

<script>

document.write(getInfo());

</script> </body></html>

Output: hello javatpoint! How r u?

JavaScript Strings

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. The syntax of creating string using
string literal is given below:

var stringname="string value";

ex: var str="This is string literal";

This is string literal

2) By string object (using new keyword)

syntax : var stringname=new String("string literal");

Here, new keyword is used to create instance of string.

Ex:

var stringname=new String("hello javascript string");

JavaScript String Methods

1.indexOf(): indexOf() method is used to search the position of a particular character or


string in a sequence of given char values. This method is case-sensitive.

The index position of first character in a string is always starts with zero. If an element is
not present in a string, it returns -1.

Syntax: string.indexOf(ch)

2.charAt()

The JavaScript string charAt() method is used to find out a char value present at the
specified index in a string.

Syntax String.charAt(index)
3) lastIndexOf(str) Method

The JavaScript String lastIndexOf(str) method returns the last index position of the given
string.

Syntax String.lastIndexOf(ch)

4) toLowerCase()

The JavaScript String toLowerCase() method returns the given string in lowercase letters.

Syntax: string.toLowerCase()

5) JavaScript String toUpperCase() Method

The JavaScript String toUpperCase() method returns the given string in uppercase
letters.

Syntax: string.toUpperCase()

6) slice(beginIndex, endIndex) Method

The JavaScript String slice(beginIndex, endIndex) method returns the parts of string
from given beginIndex to endIndex. In slice() method, beginIndex is inclusive and
endIndex is exclusive.

Syntax string.slice(start,end)

7) JavaScript String trim() Method

The JavaScript String trim() method removes leading and trailing whitespaces from the
string.

Syntax :string.trim();

8) split() Method:
Split method splits the given string.

Syntax: string.split();
Example: <!DOCTYPE html>

<html>

<body>

<script>

var str="Learn JavaScript";

document.write(“index of a is”+str.indexOf('a'));

document.writeln(“character at 4 place”+str.charAt(4));

document.writeln(“last index of a”+str.lastIndexOf("a");

var s2=str.toLowerCase();

document.write(“the lower form of string is”+s2);

var s3=str.toUpperCase();

document.write(“the upper form of string”+s3);

var s4=str.slice(2,5);

document.write(“the sub string”+s4);

var s5=”java script”;

document.write(“after the trim the string is”+s5);

</script></body></html>

Output:: index of a is 2

character at 4 place n

last index of a 8

the lower form of string is learn javascript

the upper form of string LEARN JAVASCRIPT


the sub string arn

after the trim the string is java script

JavaScript Array

JavaScript array is an object that represents a collection of similar type of elements.

There are 3 ways to construct array in JavaScript

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

1) creating an array by array literal

Syntax: var arrayname=[value1,value2.....valueN];

As you can see, values are contained inside [ ] and separated by , (comma).

EX: <html>

<body>

<script>

var emp=["Sonoo","Vimal","Ratan"];

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br/>");

</script>

</body>

</html>

The .length property returns the length of an array.


Output of the above example

Sonoo
Vimal
Ratan

2) creating an array directly (new keyword)

syntax: var arrayname=new Array();

Here, new keyword is used to create instance of array.

Example:

<html>

<body>

<script>

var i;

var emp = new Array();

emp[0] = "Arun";

emp[1] = "Varun";

emp[2] = "John";

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br>");

</script>

</body></html>
Output of the above example

Arun
Varun
John

3) creating an array using constructor (new keyword)

Here, you need to create instance of array by passing arguments in constructor so that
we don't have to provide value explicitly.

<html>

<body>

<script>

var emp=new Array("Jai","Vijay","Smith");

for (i=0;i<emp.length;i++){

document.write(emp[i] + "<br>");

</script>

</body>

</html>

Output of the above example

Jai
Vijay
Smith

Array operations:
1. Traversing
2. Inserting element into array
3. Deleting element from array
4. Merging arrays
5. Searching

//deleting element form an array

<!DOCTYPE HTML>

<html>

<body>

<script>

var arr=["C","C++",”java”,"Python",”html”];

document.write(“the elements of array”+arr);

var temp=new Array(arr.length-1);

var j=0;

var ele=window.prompt(“enter the deleting element”);

for(i=0;i<arr.length;i++)

If(arr[i]==ele)

{}

else

{ temp[j]=arr[i];

j++; }

arr=temp;

document.write(“the elements in array after deletion “+arr);

</script></body></html>
Output: the elements of array C C++ java Python html

enter the deleting element html

the elements in array after deletion C C++ java Python

JavaScript Array Methods:


1)concat() :The JavaScript array concat() method combines two or more arrays and
returns a new string. This method doesn't make any change in the original array.

Syntax: array.concat(arr1,arr2,....,arrn)

arr1,arr2,....,arrn - It represent the arrays to be combined.A new array object that


represents a joined array.

2)pop():The JavaScript array pop() method removes the last element from the
given array and return that element. This method changes the length of the
original array.

Syntax: array.pop()

3)push()

The JavaScript array push() method adds one or more elements to the end of the given
array. This method changes the length of the original array.

Syntax: array.push(element1,element2....elementn)

element1,element2....elementn - The elements to be added.The original array with


added elements is returned.

4)reverse()
The JavaScript array reverse() method changes the sequence of elements of the given
array and returns the reverse sequence. In other words, the arrays last element becomes
first and the first element becomes the last. This method also made the changes in the
original array.

Syntax: array.reverse()

The original array elements in reverse order is returned.


5)join()

The JavaScript array join() method combines all the elements of an array into a string
and return a new string. We can use any type of separators to separate given array
elements.

Syntax: array.join(separator)

Separator() - It is optional. It represent the separator used between array elements.A


new string contains the array values with specified separator is returned.

//Example on array methods:

<!DOCTYPE html>

<html>

<body>

<script>

var arr1=["C","C++","Python"];

var arr2=["Java","JavaScript","Android"];

var result=arr1.concat(arr2);

document.writeln(result);

document.writeln("Extracted element: "+result.pop()+"<br>");

result.push("html");

document.writeln("elements after push : "+result+”<br>”);

var rev=result.reverse();

document.writeln(rev);

var result=rev.join()

document.write(result);
</script>

</body>

</html>

Output: C C++ Python Java JavaScript Android

Extracted element: C C++ Python Java JavaScript

elements after push : C C++ Python Java JavaScript html

html Javscript Java Python C++ C

html,Javscript,Java,Python,C++,C

JavaScript Object:

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


• A javaScript object is an entity having state and behavior (properties and
method). For example: car, pen, bike, chair, glass, keyboard, monitor etc.
• JavaScript is template based not class based. Here, we don't create class to get
the object. But, we direct create objects.

Creating Objects in JavaScript

There are 3 ways to create objects.

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

1) JavaScript Object by object literal

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

As you can see, property and value is separated by : (colon).

Example: emp={id:102,name:"Shyam Kumar",salary:40000}


2) By creating instance of Object

syntax : var objectname=new Object();

Here, new keyword is used to create object.

Example : var emp=new Object();


emp.id=101;
emp.name="Ravi Malik";
emp.salary=50000;

3) By using an Object constructor

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

syntax : var objectname=new Object(value1,value2,…,valuen);

Example e=new emp(103,"Vimal Jaiswal",30000);


function emp(id,name,salary){ this.id=id; this.name=name; this.salary=salary; }

Defining method in JavaScript Object

We can define method in JavaScript object. But before defining method, we need to add
property in the function with same name as method.

example of defining method in object is given below.

<html>

<body>

<script>

function emp(id,name,salary){

this.id=id;

this.name=name;

this.salary=salary;
this.changeSalary=changeSalary;

function changeSalary(otherSalary){

this.salary=otherSalary;

} }

e=new emp(103,"Sonoo Jaiswal",30000);

document.write(e.id+" "+e.name+" "+e.salary);

e.changeSalary(45000);

document.write("<br>"+e.id+" "+e.name+" "+e.salary);

</script> </body></html>

Output: 103 Sonoo Jaiswal 30000


103 Sonoo Jaiswal 45000

JavaScript Math

The JavaScript math object provides several constants and methods to perform
mathematical operation. Unlike date object, it

Math Methods

1)Math.sqrt(n)

The JavaScript math.sqrt(n) method returns the square root of the given number.

Example: <!DOCTYPE html>


<html>
<body>
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script> </body> </html>

Output: Square Root of 17 is: 4.123105625617661


2)Math.pow(m,n)

The JavaScript math.pow(m,n) method returns the m to the power of n that is mn.

Example: <!DOCTYPE html>

<html>

<body>

3 to the power of 4 is: <span id="p3"></span>

<script>

document.getElementById('p3').innerHTML=Math.pow(3,4);

</script> </body> </html>

Output: 3 to the power of 4 is: 81

3)Math.floor(n)

The JavaScript math.floor(n) method returns the lowest integer for the given number.
For example 3 for 3.7, 5 for 5.9 etc.

Example: <!DOCTYPE html>

<html>

<body>

Floor of 4.6 is: <span id="p4"></span>

<script>

document.getElementById('p4').innerHTML=Math.floor(4.6);

</script> </body></html>

Output: Floor of 4.6 is: 4

4)Math.ceil(n)
The JavaScript math.ceil(n) method returns the largest integer for the given number. For
example 4 for 3.7, 6 for 5.9 etc.

<!DOCTYPE html>

<html>

<body>

Ceil of 4.6 is: <span id="p5"></span>

<script>

document.getElementById('p5').innerHTML=Math.ceil(4.6);

</script> </body></html>

output: Ceil of 4.6 is: 5

5)Math.round(n)

The JavaScript math.round(n) method returns the rounded integer nearest for the given
number. If fractional part is equal or greater than 0.5, it goes to upper value 1 otherwise
lower value 0. For example 4 for 3.7, 3 for 3.3, 6 for 5.9 etc.

Example: <html>

<body>

Round of 4.3 is: <span id="p6"></span><br>

Round of 4.7 is: <span id="p7"></span>

<script>

document.getElementById('p6').innerHTML=Math.round(4.3);

document.getElementById('p7').innerHTML=Math.round(4.7);

</script> </body></html>

Output: Round of 4.3 is: 4


Round of 4.7 is: 5
6)Math.abs(n)

The JavaScript math.abs(n) method returns the absolute value for the given number. For
example 4 for -4, 6.6 for -6.6 etc.

<!DOCTYPE html>

<html>

<body>

Absolute value of -4 is: <span id="p8"></span>

<script>

document.getElementById('p8').innerHTML=Math.abs(-4);

</script></body></html>

Output: Absolute value of -4 is: 4

7)Math.abs(n)

The JavaScript math.abs(n) method returns the absolute value for the given number. For
example 4 for -4, 6.6 for -6.6 etc

Example: <html>

<body>

Absolute value of -4 is: <span id="p8"></span>

<script>

document.getElementById('p8').innerHTML=Math.abs(-4);

</script> </body></html>

Output: Absolute value of -4 is: 4


JavaScript Date Object

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)\

Date Methods

1)getDate() method returns the day for the specified date on the basis of local
time.

Syntax: dateObj.getDate()

An integer value between 1 and 31 that represents the day of the specified date.

2)getDay() getDay() method returns the value of day of the week for the specified
date on the basis of local time. The value of the day starts with 0 that represents
Sunday.

Syntax dateObj.getDay()

3)getUTCFullYear()

The JavaScript date getUTCFullYear() method returns the year for the specified date on
the basis of universal time.

syntax: dateObj.getUTCFullYear() A number that represents the year.


4)getHours() getHours() method returns the hour for the specified date on the
basis of local time.

Syntax dateObj.getHours()

An integer value between 0 and 23 that represents the hour.

5)getMonth()

The JavaScript date getMonth() method returns the integer value that represents month
in the specified date on the basis of local time. The value returned by getMonth()
method starts with 0 that represents January.

SyntaxdateObj.getMonth()

An integer value between 0 and 11 that represents the month in the specified date.

6)getMinutes() date getMinutes() method returns the minutes in the specified date
on the basis of local time.

Syntax dateObj.getMinutes()

An integer value between 0 and 59 that represents the minute.

7)getSeconds()

The JavaScript date getSeconds() method returns the seconds in the specified date on
the basis of local time.

Syntax dateObj.getSeconds()

An integer value between 0 and 59 that represents the second.

// example to print date object. It prints date and time both.


<html>
<body>
Current Date and Time:
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script> </body>
</html>
OUTPUT: Current Date and Time: 2/3/2022

JavaScript Digital Clock Example

There are two ways to set interval in JavaScript: by setTimeout() or setInterval() method.

<html>

<body>

Current Time: <span id="txt"></span>

<script>

window.onload=function(){getTime();}

function getTime(){

var today=new Date();

var h=today.getHours();

var m=today.getMinutes();

var s=today.getSeconds();

// add a zero in front of numbers<10

m=checkTime(m);

s=checkTime(s);

document.getElementById('txt').innerHTML=h+":"+m+":"+s;

setTimeout(function(){getTime()},1000);

//setInterval("getTime()",1000);//another way
function checkTime(i){

if (i<10){

i="0" + i;

return i;

</script>

</body>

</html>

Out put: Current Time: 11:09:27

BROWSER OBJECTS:
Document Object

• The document object represents the whole html document.


• When html document is loaded in the browser, it becomes a document object.
• It is the root element that represents the html document.
• It has properties and methods.
• By the help of document object, we can add dynamic content to our web page.
• it is the object of window. So window.document

Methods of document object

write("string") writes the given string on the


doucment.

writeln("string") writes the given string on the


doucment with newline character at
the end.

getElementById() returns the element having the given


id value.
getElementsByName() returns all the elements having the
given name value.

getElementsByTagName() returns all the elements having the


given tag name.

getElementsByClassName() returns all the elements having the


given class name.

1)document.getElementById()

The document.getElementById() method returns the element of specified id.

document.getElementById() method to get value of the input text. But we need to


define id for the input field.

Example:

<html><body>

<script type="text/javascript">
function getcube(){
var number=document.getElementById("number").value;
alert(number*number*number);
}
</script>
<form>
Enter No:<input type="text" id="number" name="number"/><br/>
<input type="button" value="cube" onclick="getcube()"/>
</form> </body></html>

Output: Enter No:

cube

2)document.getElementsByName()

The document.getElementsByName() method returns all the element of specified


name.

syntax : document.getElementsByName("name")
Here, name is required.

Example : <html><body>

<script type="text/javascript">
function totalelements()
{
var allgenders=document.getElementsByName("gender");
alert("Total Genders:"+allgenders.length);
}
</script>
<form>
Male:<input type="radio" name="gender" value="male">
Female:<input type="radio" name="gender" value="female">

<input type="button" onclick="totalelements()" value="Total Genders">


</form> </body></html>
Output: Male

Female
Total Genders

Browser Object Model

The Browser Object Model (BOM) is used to interact with the browser.

The default object of browser is window means you can call all the functions of window
by specifying window or directly. For example:

window.alert("hello javatpoint"); ``

is same as:

alert("hello javatpoint");

the different objects in browser objects are:

1)Window Object

The window object represents a window in browser. An object of window is created


automatically by the browser.
Window is the object of browser, it is not the object of javascript. The javascript
objects are string, array, date etc.

Methods of window object

The important methods of window object are as follows:

alert() displays the alert box containing message with ok


button.

confirm() displays the confirm dialog box containing message


with ok and cancel button.

prompt() displays a dialog box to get input from the user.

open() opens the new window.

close() closes the current window.

setTimeout() performs action after specified time like calling


function, evaluating expressions etc.

alert() : It displays alert dialog box. It has message and ok button


example: <html><body>
<script type="text/javascript">
function msg(){
alert("Hello Alert Box");
}
</script>
<input type="button" value="click" onclick="msg()"/>

</body></html>

confirm() :

It displays the confirm dialog box. It has message with ok and cancel buttons.

Example: <html>

<body>
<script type="text/javascript">
function msg()
{
var v= confirm("Are u sure?");
if(v==true)
{
alert("ok");
}
else{
alert("cancel");
}
}
</script>

<input type="button" value="delete record" onclick="msg()"/> </body</html>

prompt()

It displays prompt dialog box for input. It has message and textfield.

Example:

<html><body>

<script type="text/javascript">
function msg(){
var v= prompt("Who are you?");
alert("I am "+v);

}
</script>

<input type="button" value="click" onclick="msg()"/> </body></html>

2)History Object

The JavaScript history object represents an array of URLs visited by the user. By using
this object, you can load previous, forward or any particular page.

The history object is the window property, so it can be accessed by:


window.history

Property of history object

length returns the length of the history URLs.

Methods of history object

There are only 3 methods of history object.

forward() loads the next page.

back() loads the previous page.

go() loads the given page number.

3)Navigator Object

The JavaScript navigator object is used for browser detection. It can be used to get
browser information such as appName, appCodeName, userAgent etc.

The navigator object is the window property, so it can be accessed by:

window.navigator

Property of JavaScript navigator object

There are many properties of navigator object that returns information of the browser.

appName returns the name

appVersion returns the version

appCodeName returns the code name

cookieEnabled returns true if cookie is enabled otherwise


false

userAgent returns the user agent

language returns the language. It is supported in


Netscape and Firefox only.

userLanguage returns the user language. It is supported


in IE only.

systemLanguage returns the system language. It is


supported in IE only.

platform returns the platform e.g. Win32.

online returns true if browser is online

4)Screen Object

The JavaScript screen object holds information of browser screen. It can be used to
display screen width, height, colorDepth, pixelDepth etc.

The navigator object is the window property, so it can be accessed by:

window.screen Or, screen

Property of JavaScript Screen Object

There are many properties of screen object that returns information of the browser.

width returns the width of the screen

height returns the height of the screen

availWidth returns the available width

availHeight returns the available height

colorDepth returns the color depth

pixelDepth returns the pixel depth.


Exception Handling
• 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.

Exception Handling Statements

There are following statements that handle if any exception occurs:

o throw statements
o try…catch statements
o try…catch…finally statements.

try…catch

Syntax:
try{
expression; }
catch(error){
expression; }

try…catch example:
<html>

<head> Exception Handling</br></head>

<body>

<script>

try{

var a= ["34","32","5","31","24","44","67"]; //a is an array

document.write(a); // displays elements of a


document.write(b); //b is undefined but still trying to fetch its value. Thus catch block will be
invoked

}catch(e){

alert("There is error which shows "+e.message); //Handling error

</script>

</body>

</html>

Output: Exception Handling


34,32,5,31,24,44,67

RegExp Object
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both String and RegExp define
methods that use regular expressions to perform powerful pattern-matching and search-and-
replace functions on text.

Syntax
A regular expression could be defined with the RegExp () constructor, as follows −

var pattern = new RegExp(pattern, attributes);

or

var pattern = /pattern/attributes;


Here is the description of the parameters −
• pattern − A string that specifies the pattern of the regular expression or another regular
expression.
• attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global,
case-insensitive, and multi-line matches, respectively.
Modifiers
Modifiers are used to perform case-insensitive and global searches:

Modifier Description

g Perform a global match (find all matches rather


than stopping after the first match)

i Perform case-insensitive matching

m Perform 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

RegExp Object Methods

Method Description

compile() Deprecated in version 1.5. Compiles a regular


expression

exec() Tests for a match in a string. Returns the first match

test() Tests for a match in a string. Returns true or false

toString() Returns the string value of the regular expression

EXAMPLE 1:

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript RegExp</h2>

<p>The exec() method tests for a match in a string:</p>

<p>Search a string for the character "e":</p>

<p id="demo"></p>

<script>
let text = "The best things in life are free";

let result = /e/.exec(text);

document.getElementById("demo").innerHTML = result;

</script>

</body>

</html>

JavaScript RegExp
The exec() method tests for a match in a string:

Search a string for the character "e":

EXAMPLE 2:

<html>

<head>

<title>JavaScript RegExp exec Method</title>

</head>

<body>

<script type = "text/javascript">

var str = "Javascript is an interesting scripting language";

var re = new RegExp( "script", "g" );

var result = re.exec(str);

document.write("Test 1 - returned value : " + result);

re = new RegExp( "pushing", "g" );

var result = re.exec(str);

document.write("<br />Test 2 - returned value : " + result);

</script>
</body></html>

Output
Test 1 - returned value : script
Test 2 - returned value : null

You might also like