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

Unit-5 Java Script Minors

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
3 views86 pages

Unit-5 Java Script Minors

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 86

JavaScript

JavaScript is a lightweight, interpreted programming language.


● It is designed for creating network-centric applications.
● It is 00 to and integrated with Java.
● JavaScript is very easy to implement because it is integrated with HTML.
● It is open and cross-platform.

● 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 the world's most popular programming language.
● JavaScript is the programming language of the Web.
● JavaScript is easy to learn.

Applications of Javascript Programming

As mentioned before, Javascript is one of the most widely used programming languages (Front-end
as well as Back-end). It has it's presence in almost every area of software development. I'm going to list
few of them here:

● Client side validation - This is really important to verify any user input before submitting it to
the server and Javascript plays an important role in validting those inputs at front-end itself.
● Manipulating HTML Pages - Javascript helps in manipulating HTML page on the fly. This
helps in adding and deleting any HTML tag very easily using javascript and modify your HTML
to change its look and feel based on different devices and requirements.
● User Notifications - You can use Javascript to raise dynamic pop-ups on the webpages to give
different types of notifications to your website visitors.
● Back-end Data Loading - Javascript provides Ajax library which helps in loading back-end data
while you are doing some other processing. This really gives an amazing experience to your
website visitors.
● Presentations - JavaScript also provides the facility of creating presentations which gives
website look and feel. JavaScript provides RevealJS and BespokeJS libraries to build a web-
based slide presentations

1
Advantages of JavaScript

The merits of using JavaScript are −

● Less server interaction − You can validate user input before sending the
page to the server. This saves server traffic, which means less load
on your server.
● Immediate feedback to the visitors − They don't have to wait for a page reload
to see if they have forgotten to enter something.
● Increased interactivity − You can create interfaces that react when the
user hovers over them with a mouse or activates them via the
keyboard.
● Richer interfaces − You can use JavaScript to include such items as drag-
and-drop components and sliders to give a Rich Interface to your
site visitors.

Client-Side JavaScript

Client-side JavaScript is the most common form of the language. The script should be included in or
referenced by an HTML document for the code to be interpreted by the browser.

It means that a web page need not be a static HTML, but can include programs that interact with the
user, control the browser, and dynamically create HTML content.

The JavaScript client-side mechanism provides many advantages over traditional CGI server-side
scripts. For example, you might use JavaScript to check if the user has entered a valid e-mail address in
a form field.

The JavaScript code is executed when the user submits the form, and only if all the entries are valid,
they would be submitted to the Web Server.

JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.

You can place the <script> tags, containing your JavaScript, anywhere within your web page, but it is
normally recommended that you should keep it within the <head> tags.

The <script> tag alerts the browser program to start interpreting all the text between these tags as a
script. A simple syntax of your JavaScript will appear as follows.

2
<script ...>
JavaScript code
</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".

So your JavaScript segment will look like −

<script language = "javascript" type = "text/javascript">


JavaScript code
</script>

Whitespace and Line Breaks

JavaScript ignores spaces, tabs, and newlines that appear in JavaScript programs.

You can use spaces, tabs, and newlines freely in your program and you are free to format and indent
your programs in a neat and consistent way that makes the code easy to read and understand.

JavaScript Datatypes
One of the most fundamental characteristics of a programming language is the set of data types it
supports. These are the type of values that can be represented and manipulated in a programming
language.

JavaScript allows you 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.

3
JavaScript Variables
Like many other programming languages, JavaScript has variables. Variables can be thought of as
named containers. You can place data into these containers and then refer to the data simply by naming
the container.

Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the
var keyword as follows.

<script type = "text/javascript">


<!--
var money;
var name;
//-->
</script>

You can also declare multiple variables with the same var keyword as follows −

<script type = "text/javascript">


<!--
var money, name;
//-->
</script>
In a programming language, variables are used to store data values.

JavaScript uses the keywords var, let and const to declare variables.

An equal sign is used to assign values to variables.


JavaScript Variable Names
While naming your variables in JavaScript, keep the following rules in mind.

● You 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 variable names should not start with a numeral (0-9). They must begin with a letter or
an underscore character. For example, 123test is an invalid variable name but _123test is a valid
one.
● JavaScript variable names are case-sensitive. For example, Name and name are two different
variables.

4
In this example, x is defined as a variable. Then, x is assigned (given) the value 6:

Example:

let x;

x = 6;

<!DOCTYPE html>

<html>

<body>

<h2>JavaScript Variables</h2>

<p>In this example, x is defined as a variable.

Then, x is assigned the value of 6:</p>

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

<script>

let x;

x = 6;

document.write( x);

</script>

</body>

</html>

5
JavaScript is untyped language. This means that a JavaScript variable can hold a value of any data type.
Unlike many other languages, you don't have to tell JavaScript during variable declaration what type of
value the variable will hold. The value type of a variable can change during the execution of a program
and JavaScript takes care of it automatically.

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 else instanceof switch

boolean enum int synchronized

break export interface this

byte extends long throw

case false native throws

catch final new transient

char finally null true

class float package try

const for private typeof

continue function protected var

debugger goto public void

default if return volatile

delete implements short while

6
do import static with

double in super

JavaScript supports the following types of operators.

● Arithmetic Operators
● Comparison Operators
● Logical (or Relational) Operators
● Assignment Operators
● Conditional (or ternary) Operators

Lets have a look on all operators one by one.

Arithmetic Operators
JavaScript supports the following arithmetic operators −

Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

1 + (Addition)

Adds two operands

Ex: A + B will give 30

2 - (Subtraction)

Subtracts the second operand from the first

Ex: A - B will give -10

3 * (Multiplication)

Multiply both operands

Ex: A * B will give 200

7
4 / (Division)

Divide the numerator by the denominator

Ex: B / A will give 2

5 % (Modulus)

Outputs the remainder of an integer division

Ex: B % A will give 0

6 ++ (Increment)

Increases an integer value by one

Ex: A++ will give 11

7 -- (Decrement)

Decreases an integer value by one

Ex: A-- will give 9

Note − Addition operator (+) works for Numeric as well as Strings. e.g. "a" +
10 will give "a10".

Example on arithmetic operators

Example

The following code shows how to use arithmetic operators in JavaScript.

<html>
<body>

<script type="text/javascript">
<!--
var a = 33;
var b = 10;

8
var c = "Test";
var linebreak = "<br />";

document.write("a + b = ");
result = a + b;
document.write(result);
document.write(linebreak);

document.write("a - b = ");
result = a - b;
document.write(result);
document.write(linebreak);

document.write("a / b = ");
result = a / b;
document.write(result);
document.write(linebreak);

document.write("a % b = ");
result = a % b;
document.write(result);
document.write(linebreak);

document.write("a + b + c = ");
result = a + b + c;
document.write(result);
document.write(linebreak);

a = ++a;
document.write("++a = ");
result = ++a;
document.write(result);
document.write(linebreak);

b = --b;
document.write("--b = ");
result = --b;
document.write(result);
document.write(linebreak);
//-->

9
</script>

Set the variables to different values and then try...


</body>
</html>

OUTPUT
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
++a = 35
--b = 8

Comparison Operators
JavaScript supports the following comparison operators −

Assume variable A holds 10 and variable B holds 20, then −

Sr.No. 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.

10
3 > (Greater than)

Checks if the value of the left operand is greater than the value of the right 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 to)

Checks if the value of the left operand is greater than or equal to the value of the
right operand, if yes, then 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
JavaScript supports the following logical operators −

Assume variable A holds 10 and variable B holds 20, then −

Sr.No. Operator & Description

11
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.

Example:

<html>
<body>

<script type="text/javascript">
<!--
var a = 95;
var b = false;
var linebreak = "<br />";

document.write("(a && b) => ");


result = (a && b);
document.write(result);
document.write(linebreak);

document.write("(a || b) => ");


result = (a || b);
document.write(result);
document.write(linebreak);

12
document.write("!(a && b) => ");
result = (!(a && b));
document.write(result);
document.write(linebreak);
//-->
</script>

<p>Set the variables to different values and different operators


and then try...</p>
</body>
</html>

OUTPUT:
(a && b) => false
(a || b) => true
!(a && b) => true

Bitwise Operators

JavaScript supports the following bitwise operators −

Assume variable A holds 2 and variable B holds 3, then −

Sr.No. 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.

13
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 is 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.

>>> (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.

14
Example:
<html>
<body>

<script type="text/javascript">
<!--
var a = 2; // Bit presentation 10
var b = 3; // Bit presentation 11
var linebreak = "<br />";

document.write("(a & b) => ");


result = (a & b);
document.write(result);
document.write(linebreak);

document.write("(a | b) => ");


result = (a | b);
document.write(result);
document.write(linebreak);

document.write("(a ^ b) => ");


result = (a ^ b);
document.write(result);
document.write(linebreak);

document.write("(~b) => ");


result = (~b);
document.write(result);
document.write(linebreak);

document.write("(a << b) => ");


result = (a << 2);
document.write(result);
document.write(linebreak);

document.write("(a >> b) => ");


result = (16 >> 2);
document.write(result);
document.write(linebreak);
//-->

15
</script>

<p>Set the variables to different values and different operators


and then try...</p>
</body>
</html>

OUTPUT:
(a & b) => 2
(a | b) => 3
(a ^ b) => 1
(~b) => -4
(a << b) => 8
(a >> b) => 4

Assignment Operators

JavaScript supports the following assignment operators −

Sr.No. Operator & Description

= (Simple Assignment )
1
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

+= (Add and Assignment)


2
It adds the right operand to the left operand and assigns the result to the left operand.

Ex: C += A is equivalent to C = C + A

−= (Subtract and Assignment)


3
It subtracts the right operand from the left operand and assigns the result to the left
operand.

Ex: C -= A is equivalent to C = C - A

16
*= (Multiply and Assignment)
4
It multiplies the right operand with the left operand and assigns the result to the left
operand.

Ex: C *= A is equivalent to C = C * A

/= (Divide and Assignment)


5
It divides the left operand with the right operand and assigns the result to the left
operand.

Ex: C /= A is equivalent to C = C / A

%= (Modules and Assignment)


6
It takes modulus using two operands and assigns the result to the left operand.

Ex: C %= A is equivalent to C = C % A

Miscellaneous Operator
We will discuss two operators here that are quite useful in JavaScript: the conditional operator (? :) and
the typeof operator.

Conditional Operator (? :)

The conditional operator first evaluates an expression for a true or false value and then executes one of
the two given statements depending upon the result of the evaluation.

Sr.No. Operator and Description

? : (Conditional )
1
If Condition is true? Then value X : Otherwise value Y

Example code:
<html>

17
<body>

<script type="text/javascript">
<!--
var a = 10;
var b = 20;
var linebreak = "<br />";

document.write ("((a > b) ? 100 : 200) => ");


result = (a > b) ? 100 : 200;
document.write(result);
document.write(linebreak);

document.write ("((a < b) ? 100 : 200) => ");


result = (a < b) ? 100 : 200;
document.write(result);
document.write(linebreak);
//-->
</script>

</body>
</html>

OUTPUT:
((a > b) ? 100 : 200) => 200
((a < b) ? 100 : 200) => 100

18
typeof Operator
The typeof operator is a unary operator that is placed before its single operand, which can be of any
type. Its value is a string indicating the data type of the operand.

The typeof operator evaluates to "number", "string", or "boolean" if its operand is a number, string, or
boolean value and returns true or false based on the evaluation.

Here is a list of the return values for the typeof Operator.

Type String Returned by typeof

Number "number"

String "string"

Boolean "boolean"

Object "object"

Function "function"

Undefined "undefined"

Null "object"

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


document.write("Result => ");
document.write(result);
document.write(linebreak);

19
result = (typeof a == "string" ? "A is String" : "A is Numeric");
document.write("Result => ");
document.write(result);
document.write(linebreak);
//-->
</script>

<p>Set the variables to different values and different operators and


then try...</p>
</body>
</html>
OUTPUT
Result => B is String
Result => A is Numeric
Set the variables to different values and different operators and then
try...

When to Use JavaScript var?


Always declare JavaScript variables with var,let, orconst.

The var keyword is used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

If you want your code to run in older browser, you must use var.

When to Use JavaScript const?


If you want a general rule: always declare variables with const.

If you think the value of the variable can change, use let.

In this example, price1, price2, and total, are variables:

Example:
<!DOCTYPE html>
<html>
<body>

20
<h1>JavaScript Variables</h1>

<p>In this example, price1, price2, and total are variables.</p>

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

<script>
price1 = 5;
const price2 = 6;
price1=price1+1
let total = price1 + price2;
document.getElementById("demo").innerHTML =
"The total is: " + price1;
</script>

</body>
</html>

OUTPUT
Result => B is String
Result => A is Numeric

Set the variables to different values and different operators and


then try...

JavaScript Variables
In this example, price1, price2, and total are variables.

The total is: 6

One Statement, Many Variables


You can declare many variables in one statement.

21
Start the statement with let and separate the variables by comma:

Example
let person = "John Doe", carName = "Volvo", price = 200;

A function is a group of reusable code which can be called anywhere


in your 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. You must have seen functions like alert() and write() in
the earlier chapters. We were using these functions again and again,
but they had been written in core JavaScript only once.

JavaScript allows us to write our own functions as well. This section


explains how to write your own functions in JavaScript.

Function Definition
Before we use a function, we need to define it. The most common way
to define a function in JavaScript is by using the function keyword,
followed by a unique function name, a list of parameters (that might
be empty), and a statement block surrounded by curly braces.

Syntax

The basic syntax is shown here.

<script type = "text/javascript">


<!--
function functionname(parameter-list) {
statements
}
//-->
</script>

22
Example

Try the following example. It defines a function called sayHello that takes
no parameters −

<script type = "text/javascript">


<!--
function sayHello() {
alert("Hello there");
}
//-->
</script>

Calling a Function
To invoke a function somewhere later in the script, you would simply
need to write the name of that function as shown in the following
code.

Live Demo
<html>
<head>
<script type = "text/javascript">
function sayHello() {
document.write ("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>

23
OUTPUT:

Hello there!

JAVA SCRIPT EVENTS

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.

With single quotes:

<element event='some JavaScript'>

With double quotes:

<element event="some JavaScript">

In the following example, an onclick attribute (with code), is added to a <button> element:

<!DOCTYPE html>
<html>
<body>

24
<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>

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

</body>
</html>

In the next example, the code changes the content of its own element (using
this.innerHTML):

<!DOCTYPE html>

25
<html>
<body>

<h2>JavaScript HTML Events</h2>


<button onclick="this.innerHTML=Date()">The time is?</button>

</body>
</html>
OUTPUT:

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

26
onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

JavaScript Event Handlers


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 ...

Many different methods can be used to let JavaScript work with events:

● HTML event attributes can execute JavaScript code directly


● HTML event attributes can call JavaScript functions
● You can assign your own event handler functions to HTML elements

String Length
To find the length of a string, use the built-in length property:

<!DOCTYPE html>
<html>

27
<body>

<h2>JavaScript String Properties</h2>

<p>The length property returns the length of a string:</p>

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

<script>
let text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
document.getElementById("demo").innerHTML = text.length;
</script>

</body>
</html>

OUTPUT
JavaScript String Properties
The length property returns the length of a string:

26

Common HTML Events


Here is a list of some common HTML events:

Event Description

onchange An HTML element has been changed

onclick The user clicks an HTML element

onmouseover The user moves the mouse over an HTML element

onmouseout The user moves the mouse away from an HTML element

28
onkeydown The user pushes a keyboard key

onload The browser has finished loading the page

JavaScript Events
The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When javascript code is
included in HTML, js react over these events and allow the execution. This process of reacting over the
events is called Event Handling. Thus, js handles the HTML events via Event Handlers.

For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.

Some of the HTML events and their event handlers are:

Mouse events:
Event Performed Event Handler Description

click onclick When mouse click on an element

mouseover onmouseover When the cursor of the mouse comes over the
element

mouseout onmouseout When the cursor of the mouse leaves an element

mousedown onmousedown When the mouse button is pressed over the element

mouseup onmouseup When the mouse button is released over the element

29
mousemove onmousemove When the mouse movement takes place.

Keyboard events:
Event Performed Event Handler Description

Keydown & Keyup onkeydown & onkeyup When the user press and then release the key

Form events:
Event Performed Event Handler Description

focus onfocus When the user focuses on an element

submit onsubmit When the user submits the form

blur onblur When the focus is away from a form element

change onchange When the user modifies or changes the value of a form
element

Window/Document events
Event Performed Event Handler Description

load onload When the browser finishes the loading of the page

30
unload onunload When the visitor leaves the current webpage, the
browser unloads it

resize onresize When the visitor resizes the window of the browser

Example of mouse over event


<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>

31
Example of Focus Event
1. <html>
2. <head> Javascript Events</head>
3. <body>
4. <h2> Enter something here</h2>
5. <input type="text" id="input1" onfocus="focusevent()"/>
6. <script>
7. <!--
8. function focusevent()
9. {
10. document.getElementById("input1").style.background=" aqua";
11. }
12. //-->
13. </script>
14. </body>
15. </html>

Test it Now

32
OUTPUT:

Keydown Event
Example
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{

alert("Pressed a key");
}
//-->
</script>
</body>
</html>

33
OUTPUT

Load event
1. <html>
2. <head>Javascript Events
3.
a. <script>
b. <!--
c. document.write("The page is loaded successfully");
d. //-->
e. </script>
4.
5. </head>
6. </br>
7. <body onload="window.alert('Page successfully loaded');">
8.
9. </body>
10. </html>

Output:

34
onfocusin Event
EXAMPLE:
<!DOCTYPE html>

<html>

<body>

Enter your name: <input type="text" onfocusin="myFunction(this)">

<p>When the input field gets focus, a function is triggered which changes the background-color.</p>

<script>

function myFunction(x) {

x.style.background = "yellow";

35
</script>

</body>

</html>

Output:

onfocusout Event
Definition and Usage
The onfocusout event occurs when an element is about to lose focus.

Tip: The onfocusout event is similar to the onblur event. The main difference is that the onblur event
does not bubble. Therefore, if you want to find out whether an element or its child loses focus, you
should use the onfocusout event.

Tip: The onfocusout event is the opposite of the onfocusin event.

example:
<!DOCTYPE html>
<html>
<body>

Enter your name: <input type="text" id="fname" onfocusout="myFunction()">

<p>When you leave the input field, a function is triggered which transforms the input text to upper
case.</p>

36
<script>
function myFunction() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script>

</body>
</html>

OUTPUT:

For all types of events click the following link

https://www.w3schools.com/jsref/dom_obj_event.asp

37
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example: car,
pen, bike, chair, glass, keyboard, monitor etc.

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

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

Creating Objects in JavaScript


There are 3 ways to create objects.

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

1) JavaScript Object by object literal


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

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

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

Let’s see the simple example of creating object in JavaScript.

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

OUTPUT:
102 Shyam Kumar 40000

38
2) By creating instance of Object
The syntax of creating object directly is given below:

1. var objectname=new Object();

Here, new keyword is used to create object.

Let’s see the example of creating object directly.

1. <script>
2. var emp=new Object();
3. emp.id=101;
4. emp.name="Ravi Malik";
5. emp.salary=50000;
6. document.write(emp.id+" "+emp.name+" "+emp.salary);
7. </script>

Output of the above example


101 Ravi 50000

3) By using an Object constructor


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

The this keyword refers to the current object.

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

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6. }
7. e=new emp(103,"Vimal Jaiswal",30000);
8.
9. document.write(e.id+" "+e.name+" "+e.salary);
10. </script>

39
Output of the above example
103 Vimal Jaiswal 30000

Defining method in JavaScript Object


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

The example of defining method in object is given below.

1. <script>
2. function emp(id,name,salary){
3. this.id=id;
4. this.name=name;
5. this.salary=salary;
6.
7. this.changeSalary=changeSalary;
8. function changeSalary(otherSalary){
9. this.salary=otherSalary;
10. }
11. }
12. e=new emp(103,"Sonoo Jaiswal",30000);
13. document.write(e.id+" "+e.name+" "+e.salary);
14. e.changeSalary(45000);
15. document.write("<br>"+e.id+" "+e.name+" "+e.salary);
16. </script>

Output of the above example


103 Sonoo Jaiswal 30000
103 Sonoo Jaiswal 45000

Let's see the simple example of creating and using array in JavaScript.

1. <script>
2. var emp=["Sonoo","Vimal","Ratan"];
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br/>");
5. }
6. </script>

40
Test it Now

The .length property returns the length of an array.

Output of the above example

Sonoo
Vimal
Ratan

2) JavaScript Array directly (new keyword)


The syntax of creating array directly is given below:

1. var arrayname=new Array();

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

Let's see the example of creating array directly.

1. <script>
2. var i;
3. var emp = new Array();
4. emp[0] = "Arun";
5. emp[1] = "Varun";
6. emp[2] = "John";
7.
8. for (i=0;i<emp.length;i++){
9. document.write(emp[i] + "<br>");
10. }
11. </script>

Test it Now

Output of the above example

Arun
Varun
John

3) JavaScript array constructor (new keyword)

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

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

1. <script>
2. var emp=new Array("Jai","Vijay","Smith");
3. for (i=0;i<emp.length;i++){
4. document.write(emp[i] + "<br>");
5. }
6. </script>

Test it Now

Output of the above example

Jai
Vijay
Smith

JavaScript Array Methods


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

Methods Description

concat() It returns a new array object that contains two or more merged arrays.

copywithin() It copies the part of the given array with its own elements and returns the
modified array.

entries() It creates an iterator object and a loop that iterates over each key/value pair.

every() It determines whether all the elements of an array are satisfying the provided
function conditions.

42
1. <script>
2. var str="This is string literal";
3. document.write(str);
4. </script>

Test it Now

Output:

This is string literal

2) By string object (using new keyword)


The syntax of creating string object using new keyword is given below:

1. var stringname=new String("string literal");

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

Let's see the example of creating string in JavaScript by new keyword.

1. <script>
2. var stringname=new String("hello javascript string");
3. document.write(stringname);
4. </script>

Test it Now

Output:

hello javascript string

JavaScript String Methods


Let's see the list of JavaScript string methods with examples.

43
Methods Description

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

charCodeAt() It provides the Unicode value of a character present at the


specified index.

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

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

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

search() It searches a specified regular expression in a given string and


returns its position if a match occurs.

match() It searches a specified regular expression in a given string and


returns that regular expression if a match occurs.

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

substr() It is used to fetch the part of the given string on the basis of the
specified starting position and length.

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

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

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

toLocaleLowerCase() It converts the given string into lowercase letter on the basis of
host?s current locale.

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

toLocaleUpperCase() It converts the given string into uppercase letter on the basis of
host?s current locale.

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

valueOf() It provides the primitive value of string object.

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

trim() It trims the white space from the left and right side of the string.

1) JavaScript String charAt(index) Method


The JavaScript String charAt() method returns the character at the given index.

1. <script>
2. var str="javascript";
3. document.write(str.charAt(2));
4. </script>

Test it Now

Output:

45
2) JavaScript String concat(str) Method
The JavaScript String concat(str) method concatenates or joins two strings.

1. <script>
2. var s1="javascript ";
3. var s2="concat example";
4. var s3=s1.concat(s2);
5. document.write(s3);
6. </script>

Test it Now

Output:

javascript concat example

3) JavaScript String indexOf(str) Method


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

1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.indexOf("from");
4. document.write(n);
5. </script>

Test it Now

Output:

11

4) JavaScript String lastIndexOf(str) Method


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

1. <script>
2. var s1="javascript from javatpoint indexof";
3. var n=s1.lastIndexOf("java");

46
4. document.write(n);
5. </script>

Test it Now

Output:

16

5) JavaScript String toLowerCase() Method


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

1. <script>
2. var s1="JavaScript toLowerCase Example";
3. var s2=s1.toLowerCase();
4. document.write(s2);
5. </script>

Test it Now

Output:

javascript tolowercase example

6) JavaScript String toUpperCase() Method


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

1. <script>
2. var s1="JavaScript toUpperCase Example";
3. var s2=s1.toUpperCase();
4. document.write(s2);
5. </script>

Test it Now

Output:

JAVASCRIPT TOUPPERCASE EXAMPLE

47
7) JavaScript String 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.

1. <script>
2. var s1="abcdefgh";
3. var s2=s1.slice(2,5);
4. document.write(s2);
5. </script>

Test it Now

Output:

cde

8) JavaScript String trim() Method


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

1. <script>
2. var s1=" javascript trim ";
3. var s2=s1.trim();
4. document.write(s2);
5. </script>

Test it Now

Output:

javascript trim

9) JavaScript String split() Method

1. <script>
2. var str="This is JavaTpoint website";
3. document.write(str.split(" ")); //splits the given string.
4. </script>

48
OUTPUT:
This,is,JavaTpoint,website

What is this?
In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.

Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Methods like call(), apply(), and bind() can refer this to any object.

EXAMPLE
<!DOCTYPE html>
<html>
<body>

<h1>The JavaScript <i>this</i> Keyword</h1>


<p>In this example, <b>this</b> refers to the <b>person</b> object.</p>
<p>Because <b>fullName</b> is a method of the person object.</p>

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

49
<script>
// Create an object:
const person = {
firstName: "John",
lastName: "Doe",
id: 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

// Display data from the object:


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

</body>
</html>

LINK FOR ABOVE EXAMPLE


https://www.w3schools.com/js/tryit.asp?filename=tryjs_this_method

output

The JavaScript this Keyword


In this example, this refers to the person object.

Because fullName is a method of the person object.

John Doe

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

JavaScript Math Methods


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

Methods Description

abs() It returns the absolute value of the given number.

acos() It returns the arccosine of the given number in radians.

asin() It returns the arcsine of the given number in radians.

atan() It returns the arc-tangent of the given number in radians.

cbrt() It returns the cube root of the given number.

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

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

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

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

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

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

log() It returns natural logarithm of a number.

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

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

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

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

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

sign() It returns the sign of the given number

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

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

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

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

tanh() It returns the hyperbolic tangent of the given number.

trunc() It returns an integer part of the given number.

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

1. Square Root of 17 is: <span id="p1"></span>


2. <script>
3. document.getElementById('p1').innerHTML=Math.sqrt(17);
4. </script>

Test it Now

52
Output:

Square Root of 17 is: 4.123105625617661

Math.random()
The JavaScript math.random() method returns the random number between 0 to 1.

1. Random Number is: <span id="p2"></span>


2. <script>
3. document.getElementById('p2').innerHTML=Math.random();
4. </script>

Test it Now

Output:

Random Number is: 0.45769553636077476

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

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


2. <script>
3. document.getElementById('p3').innerHTML=Math.pow(3,4);
4. </script>

Test it Now

Output:

3 to the power of 4 is: 81

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.

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


2. <script>
3. document.getElementById('p4').innerHTML=Math.floor(4.6);

53
4. </script>

Test it Now

Output:

Floor of 4.6 is: 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.

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


2. <script>
3. document.getElementById('p5').innerHTML=Math.ceil(4.6);
4. </script>

Test it Now

Output:

Ceil of 4.6 is: 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.

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


2. Round of 4.7 is: <span id="p7"></span>
3. <script>
4. document.getElementById('p6').innerHTML=Math.round(4.3);
5. document.getElementById('p7').innerHTML=Math.round(4.7);
6. </script>

Test it Now

Output:

Round of 4.3 is: 4


Round of 4.7 is: 5

54
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.

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


2. <script>
3. document.getElementById('p8').innerHTML=Math.abs(-4);
4. </script>

Test it Now

Output:

Absolute value of -4 is: 4

JavaScript Number Object


The JavaScript number object enables you to represent a numeric value. It may be integer or floating-
point. JavaScript number object follows IEEE standard to represent the floating-point numbers.

By the help of Number() constructor, you can create number object in JavaScript. For example:

1. var n=new Number(value);

If value can't be converted to number, it returns NaN(Not a Number) that can be checked by isNaN()
method.

You can direct assign a number to a variable also. For example:

1. var x=102;//integer value


2. var y=102.7;//floating point value
3. var z=13e4;//exponent value, output: 130000
4. var n=new Number(16);//integer value by number object

Test it Now

Output:

102 102.7 130000 16

55
JavaScript Number Constants
Let's see the list of JavaScript number constants with description.

Constant Description

MIN_VALUE returns the largest minimum value.

MAX_VALUE returns the largest maximum value.

POSITIVE_INFINITY returns positive infinity, overflow value.

NEGATIVE_INFINITY returns negative infinity, overflow value.

NaN represents "Not a Number" value.

JavaScript Number Methods


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

Methods Description

isFinite() It determines whether the given value is a finite number.

isInteger() It determines whether the given value is an integer.

parseFloat() It converts the given string into a floating point number.

parseInt() It converts the given string into an integer number.

toExponential() It returns the string that represents exponential notation of the given
number.

56
toFixed() It returns the string that represents a number with exact digits after a
decimal point.

toPrecision() It returns the string representing a number of specified precision.

toString() It returns the given number in the form of string.

JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You can create the
JavaScript Boolean object by Boolean() constructor as given below.

1. Boolean b=new Boolean(value);

The default value of JavaScript Boolean object is false.

JavaScript Boolean Example


1. <script>
2. document.write(10<20);//true
3. document.write(10<5);//false
4. </script>

JavaScript Boolean Properties


Property Description

constructor returns the reference of Boolean function that created Boolean object.

prototype enables you to add properties and methods in Boolean prototype.

JavaScript Boolean Methods

57
Method Description

toSource() returns the source of Boolean object as a string.

toString() converts Boolean into String.

valueOf() converts other type into Boolean.

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

You can use a lot of properties (other objects) defined underneath the window object like document,
history, screen, navigator, location, innerHeight, innerWidth,

Note: The document object represents an html document. It forms DOM (Document Object Model).

Window Object

58
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.

Note: if html document contains frame or iframe, browser creates additional window objects for each
frame.

Methods of window object

The important methods of window object are as follows:

Method Description

displays the alert box containing message with ok button.

alert()

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.

Example of alert() in javascript

It displays alert dialog box. It has message and ok button.

1. <script type="text/javascript">
2. function msg(){

59
3. alert("Hello Alert Box");
4. }
5. </script>
6. <input type="button" value="click" onclick="msg()"/>

Output of the above example

Example of confirm() in javascript

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

1. <script type="text/javascript">
2. function msg(){
3. var v= confirm("Are u sure?");
4. if(v==true){
5. alert("ok");
6. }
7. else{
8. alert("cancel");
9. }
10.
11. }
12. </script>
13.
14. <input type="button" value="delete record" onclick="msg()"/>

Output of the above example

Example of prompt() in javascript

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

1. <script type="text/javascript">
2. function msg(){
3. var v= prompt("Who are you?");
4. alert("I am "+v);
5.
6. }
7. </script>
8.
9. <input type="button" value="click" onclick="msg()"/>

Output of the above example

Example of open() in javascript

It displays the content in a new window.

1. <script type="text/javascript">
2. function msg(){
3. open("http://www.javatpoint.com");
4. }
5. </script>
6. <input type="button" value="javatpoint" onclick="msg()"/>

Output of the above example

Example of setTimeout() in javascript

It performs its task after the given milliseconds.

61
1. <script type="text/javascript">
2. function msg(){
3. setTimeout(
4. function(){
5. alert("Welcome to Javatpoint after 2 seconds")
6. },2000);
7.
8. }
9. </script>
10.
11. <input type="button" value="click" onclick="msg()"/>

Output of the above example

JavaScript 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:

1. window.history

Or,

1. history

Property of JavaScript history object


There are only 1 property of history object.

62
No. Property Description

1 length returns the length of the history URLs.

Methods of JavaScript history object


There are only 3 methods of history object.

No. Method Description

1 forward() loads the next page.

2 back() loads the previous page.

3 go() loads the given page number.

Example of history object


Let’s see the different usage of history object.

1. history.back();//for previous page


2. history.forward();//for next page
3. history.go(2);//for next 2nd page
4. history.go(-2);//for previous 2nd page

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.

63
You can use different Date constructors to create date object. It provides methods to get and set day,
month, year, hour, minute and seconds.

Constructor
You can use 4 variant of Date constructor to create date object.

1. Date()
2. Date(milliseconds)
3. Date(dateString)
4. Date(year, month, day, hours, minutes, seconds, milliseconds)

JavaScript Date Methods


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

Methods Description

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

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

getFullYears() It returns the integer value that represents the year on the basis of
local time.

getHours() It returns the integer value between 0 and 23 that represents the
hours on the basis of local time.

getMilliseconds() It returns the integer value between 0 and 999 that represents the
milliseconds on the basis of local time.

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

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

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

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

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

getUTCFullYears() It returns the integer value that represents the year on the basis of
universal time.

getUTCHours() It returns the integer value between 0 and 23 that represents the
hours on the basis of universal time.

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

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

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

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

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

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

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

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

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

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

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

setUTCDate() It sets the day value for the specified date on the basis of
universal time.

setUTCDay() It sets the particular day of the week on the basis of universal
time.

setUTCFullYears() It sets the year value for the specified date on the basis of
universal time.

setUTCHours() It sets the hour value for the specified date on the basis of
universal time.

setUTCMilliseconds() It sets the millisecond value for the specified date on the basis of
universal time.

66
setUTCMinutes() It sets the minute value for the specified date on the basis of
universal time.

setUTCMonth() It sets the month value for the specified date on the basis of
universal time.

setUTCSeconds() It sets the second value for the specified date on the basis of
universal time.

toDateString() It returns the date portion of a Date object.

toISOString() It returns the date in the form ISO format string.

toJSON() It returns a string representing the Date object. It also serializes


the Date object during JSON serialization.

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

toTimeString() It returns the time portion of a Date object.

toUTCString() It converts the specified date in the form of string using UTC time
zone.

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

JavaScript Date Example

Let's see the simple example to print date object. It prints date and time both.

1. Current Date and Time: <span id="txt"></span>


2. <script>
3. var today=new Date();
4. document.getElementById('txt').innerHTML=today;
5. </script>

Test it Now

67
Output:

Current Date and Time: Wed Jul 06 2022 09:53:41 GMT+0000 (Coordinated Universal Time)

Let's see another code to print date/month/year.

1. <script>
2. var date=new Date();
3. var day=date.getDate();
4. var month=date.getMonth()+1;
5. var year=date.getFullYear();
6. document.write("<br>Date is: "+day+"/"+month+"/"+year);
7. </script>

Output:

Date is: 6/7/2022

JavaScript Current Time Example

Let's see the simple example to print current time of system.

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


2. <script>
3. var today=new Date();
4. var h=today.getHours();
5. var m=today.getMinutes();
6. var s=today.getSeconds();
7. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
8. </script>

Test it Now

Output:

Current Time: 9:53:41

68
JavaScript Digital Clock Example

Let's see the simple example to display digital clock using JavaScript date object.

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

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


2. <script>
3. window.onload=function(){getTime();}
4. function getTime(){
5. var today=new Date();
6. var h=today.getHours();
7. var m=today.getMinutes();
8. var s=today.getSeconds();
9. // add a zero in front of numbers<10
10. m=checkTime(m);
11. s=checkTime(s);
12. document.getElementById('txt').innerHTML=h+":"+m+":"+s;
13. setTimeout(function(){getTime()},1000);
14. }
15. //setInterval("getTime()",1000);//another way
16. function checkTime(i){
17. if (i<10){
18. i="0" + i;
19. }
20. return i;
21. }
22. </script>

Test it Now

Output:

Current Time: 9:55:39

69
What is the Document Object Model?
1. The Document Object Model (DOM) is a programming
API for HTML and XML documents. It defines the logical
structure of documents and the way a document is
accessed and manipulated
2. With the Document Object Model, programmers can
create and build documents, navigate their structure,
and add, modify, or delete elements and content.
3. Anything found in an HTML or XML document can be
accessed, changed, deleted, or added using the
Document Object Model.

What the Document Object Model is

The Document Object Model is a programming API for


documents. The object model itself closely resembles the
structure of the documents it models. For instance, consider
this table, taken from an HTML document:
<TABLE>
<ROWS>
<TR>

70
<TD>Shady Grove</TD>
<TD>Aeolian</TD>
</TR>
<TR>
<TD>Over the River, Charlie</TD>
<TD>Dorian</TD>
</TR>
</ROWS>
</TABLE>

The Document Object Model represents this table like this:

With the object model, JavaScript gets all the power it needs to create dynamic HTML:

● JavaScript can change all the HTML elements in the page


● JavaScript can change all the HTML attributes in the page
● JavaScript can change all the CSS styles in the page
● JavaScript can remove existing HTML elements and attributes
● JavaScript can add new HTML elements and attributes
● JavaScript can react to all existing HTML events in the page

71
● JavaScript can create new HTML events in the page

What is the HTML DOM?


The HTML DOM is a standard object model and programming interface for HTML. It
defines:

● The HTML elements as objects


● The properties of all HTML elements
● The methods to access all HTML elements
● The events for all HTML elements

In other words: The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.

Document Object Model


1. Document Object
2. Properties of document object
3. Methods of document object
4. Example of 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.

As mentioned earlier, it is the object of window. So

1. window.document

Is same as

72
1. document

According to W3C - "The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update the content,
structure, and style of a document."

Properties of document object


Let's see the properties of document object that can be accessed and modified by the document
object.

Methods of document object


We can access and change the contents of document by its methods.

73
The important methods of document object are as follows:

Method Description

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.

Changing HTML Elements

Property Description

74
element.innerHTML = new html content Change the inner HTML of an element

element.attribute = new value Change the attribute value of an HTML


element

element.style.property = new style Change the style of an HTML element

Method Description

element.setAttribute(attribute, value) Change the attribute value of an HTML


element

Accessing field value by document object


In this example, we are going to get the value of input text by user. Here, we are using
document.form1.name.value to get the value of name field.

Here, document is the root element that represents the html document.

form1 is the name of the form.

name is the attribute name of the input text.

75
value is the property, that returns the value of the input text.

Let's see the simple example of document object that prints name with welcome message.

1. <script type="text/javascript">
2. function printvalue(){
3. var name=document.form1.name.value;
4. alert("Welcome: "+name);
5. }
6. </script>
7.
8. <form name="form1">
9. Enter Name:<input type="text" name="name"/>
10. <input type="button" onclick="printvalue()" value="print name"/>
11. </form>

Output of the above example

Javascript - document.getElementById() method


1. getElementById() method
2. Example of getElementById()

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

76
In the previous page, we have used document.form1.name.value to get the value of the input
value. Instead of this, we can use document.getElementById() method to get value of the input
text. But we need to define id for the input field.

Let's see the simple example of document.getElementById() method that prints cube of the given
number.

1. <script type="text/javascript">
2. function getcube(){
3. var number=document.getElementById("number").value;
4. alert(number*number*number);
5. }
6. </script>
7. <form>
8. Enter No:<input type="text" id="number" name="number"/><br/>
9. <input type="button" value="cube" onclick="getcube()"/>
10. </form>

Output of the above example

77
Javascript - document.getElementsByName()
method
1. getElementsByName() method
2. Example of getElementsByName()

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

The syntax of the getElementsByName() method is given below:

1. document.getElementsByName("name")

Here, name is required.

Example of document.getElementsByName() method

In this example, we going to count total number of genders. Here, we are using
getElementsByName() method to get all the genders.

78
1. <script type="text/javascript">
2. function totalelements()
3. {
4. var allgenders=document.getElementsByName("gender");
5. alert("Total Genders:"+allgenders.length);
6. }
7. </script>
8. <form>
9. Male:<input type="radio" name="gender" value="male">
10. Female:<input type="radio" name="gender" value="female">
11.
12. <input type="button" onclick="totalelements()" value="Total Genders">
13. </form>

Output of the above example

79
Javascript - innerHTML
1. javascript innerHTML
2. Example of innerHTML property

The innerHTML property can be used to write the dynamic html on the html document.

It is used mostly in the web pages to generate the dynamic html such as registration form,
comment form, links etc.

Example of innerHTML property


<html>
<body>
<script type="text/javascript" >
function showcommentform()
{
var data="Name:<br><input type='text' name='name'><br>Comment:<br><textarea rows='5'
cols='50'></textarea><br><input type='submit' value='comment'>";

document.getElementById('mylocation').innerHTML=data;
}

</script>
<form name="myForm">
<input type="button" value="comment" onclick="showcommentform()">
<div id="mylocation"></div>
</form>
</body>
</html>

80
Show/Hide Comment Form Example using innerHTML
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <title>First JS</title>
5. <script>
6. var flag=true;
7. function commentform(){
8. var cform="<form action='Comment'>Enter Name:<br><input type='text'
name='name'/><br/>
9. Enter Email:<br><input type='email' name='email'/><br>Enter Comment:<br/>
10. <textarea rows='5' cols='70'></textarea><br><input type='submit' value='Post
Comment'/></form>";
11. if(flag){
12. document.getElementById("mylocation").innerHTML=cform;
13. flag=false;
14. }else{
15. document.getElementById("mylocation").innerHTML="";
16. flag=true;
17. }
18. }
19. </script>
20. </head>
21. <body>
22. <button onclick="commentform()">Comment</button>
23. <div id="mylocation"></div>
24. </body>
25. </html>

81
Javascript - innerText
1. javascript innerText
2. Example of innerText property

The innerText property can be used to write the dynamic text on the html document. Here, text
will not be interpreted as html text but a normal text.

It is used mostly in the web pages to generate the dynamic content such as writing the validation
message, password strength etc.

82
Javascript innerText Example
In this example, we are going to display the password strength when releases the key after press.

<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" >
function validate() {
var msg;
if(document.myForm.userPass.value.length>5){
msg="good";
}
else{
msg="poor";
}
document.getElementById('mylocation').innerText=msg;
}

</script>
<form name="myForm">
<input type="password" value="" name="userPass" onkeyup="validate()">
Strength:<span id="mylocation">no strength</span>
</form>

</body>
</html>

Output of the above example

JavaScript Form Validation

83
1. JavaScript form validation
2. Example of JavaScript validation
3. JavaScript email validation

It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user.

JavaScript provides facility to validate the form on the client-side so data processing will be
faster than server-side validation. Most of the web developers prefer JavaScript form validation.

Through JavaScript, we can validate name, password, email, date, mobile numbers and more
fields.

JavaScript Form Validation Example


In this example, we are going to validate the name and password. The name can’t be empty and
password can’t be less than 6 characters long.

54.9M

1.2K

Features of Java - Javatpoint

Here, we are validating the form on form submit. The user will not be forwarded to the next page
until given values are correct.

<html>
<body>
<script>
function validateform(){
var name=document.myform.name.value;
var password=document.myform.password.value;

if (name==null || name==""){
alert("Name can't be blank");
return false;
}else if(password.length<6){
alert("Password must be at least 6 characters long.");
return false;
}

84
}
</script>
<body>
<form name="myform" method="post"
action="http://www.javatpoint.com/javascriptpages/valid.jsp" 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 Retype Password Validation


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function matchpass(){
var firstpassword=document.f1.password.value;
var secondpassword=document.f1.password2.value;

if(firstpassword==secondpassword){
return true;

85
}
else{
alert("password must be same!");
return false;
}
}
</script>
</head>
<body>

<form name="f1" action="http://www.javatpoint.com/javascriptpages/valid.jsp"


onsubmit="return matchpass()">
Password:<input type="password" name="password" /><br/>
Re-enter Password:<input type="password" name="password2"/><br/>
<input type="submit">
</form>

</body>
</html>

OUTPUT:

86

You might also like