Javascript
Javascript
JAVASCRIPT: INTRODUCTION
JavaScript is a programming language that can be included on web
pages to make them more interactive. We can use it to check or modify the
contents of forms, change images, open new windows and write dynamic
page content. We can even use it with CSS to make DHTML (Dynamic
HyperText Markup Language). This allows we to make parts of our web pages
appear or disappear or move around on the page. JavaScripts only execute on
the page(s) that are on our browser window at any set time. When the user
stops viewing that page, any scripts that were running on it are immediately
stopped. The only exceptions are cookies or various client side storage APIs,
which can be used by many pages to store and pass information between
them, even after the pages have been closed.
Page 1
Client-side programming runs on the user's computer. The programs
are passed to the computer that the browser is on, and that computer runs the
script. But the problem is the limit of control and problems with operating
systems and web browsers.
SCRIPT TAG
The <SCRIPT> tag alerts a browser that JavaScript code follows. It is
typically embedded in the HTML. The <script> tag is used to define a client-
side script, such as a JavaScript. The <script> element either contains
scripting statements, or it points to an external script file through the src
attribute. Common uses for JavaScript are image manipulation, form
validation, and dynamic changes of content. The script tag has two purposes:
src="url"
The src attribute is optional. If it is present, then its value is a url which
identifies a .js file. The loading and processing of the page pauses while the
browser fetches, compiles, and executes the file. The content between the
<script src="url"> and the </script>should be blank.
language="javascript"
This attribute has been deprecated. It was used to select other programming
languages and specific versions of JavaScript. You don't need it. Don't use it.
type="text/javascript"
This attribute is optional. Since Netscape 2, the default programming
language in all browsers has been JavaScript. In XHTML, this attribute is
required and unnecessary. In HTML, it is better to leave it out. The browser
knows what to do.
<SCRIPT language = "JavaScript">
statements
</SCRIPT>
Example
<html><head>
<SCRIPT type="text/javascript">
alert("Welcome to the script tag test page.");
</SCRIPT>
</head> <body>
<h2>Good Morning</h2>
</body> </html>
Page 2
Save the changes by choosing Save from the File menu.
Then Refresh the browser by clicking the Refresh or Reload button.
JAVASCRIPT COMMENTS
Comments can be added to explain the JavaScript, or to make the
code more readable. Single line comments start with //. The following
example uses single line comments to explain the code:
Example
<script type="text/javascript">
// Write a heading
document.write("<h1>This is a heading</h1>");
// Write two paragraphs:
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
JavaScript Multi-Line Comments
Multi line comments start with /* and end with */. The following
example uses a multi line comment to explain the code:
Example
<script type="text/javascript">
/*
The code below will write
one heading and two paragraphs
*/
document.write("<h1>This is a heading</h1>");
document.write("<p>This is a paragraph.</p>");
document.write("<p>This is another paragraph.</p>");
</script>
Using Comments at the End of a Line
In the following example the comment is placed at the end of a code line:
Example
<script type="text/javascript">
document.write("Hello"); // Write "Hello"
document.write(" Dolly!"); // Write " Dolly!"
</script>
VARIABLES
Variables are used to store data. A variable's value can change during
the execution of a script. We can refer to a variable by its name to display or
change its value. The rules for JavaScript variable names:
Variable names are case sensitive (y and Y are two different variables)
Variable names must begin with a letter, the $ character, or the
underscore character
Because JavaScript is case-sensitive, variable names are case-sensitive.
Page 3
Declaring JavaScript Variables
Creating variables in JavaScript is most often referred to as "declaring"
variables. We declare JavaScript variables with the var keyword:
var x;
var carname;
After the declaration shown above, the variables are empty (they have no values
yet). However, we can also assign values to the variables when we declare them:
var x=5;
var carname="Volvo";
After the execution of the statements above, the variable x will hold the value 5,
and carname will hold the value Volvo. When we assign a text value to a
variable, use quotes around the value. If we re-declare a JavaScript variable, it
will not lose its value.
Page 4
2. Within <body> tag
<!DOCTYPE html>
<html lang="en">
<head>
<title>Embedding JavaScript</title>
</head> <body>
<div id="greet"></div>
<script>
document.getElementById("greet").innerHTML = "Hello World!";
</script>
</body> </html>
</script>
</head> <body>
<H2> Hello JavaScript </H2>
<p>Welcome to GEMS College</p>
</body> </html>
alert("Good Afternoon");
alert("Helloo");
DATA TYPES
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
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 (Complex) data type
Page 5
Primitive data type
String:- Strings are used for storing text. Strings must be inside of either
double or single quotes.
var str1 = "It is alright, ";
var str2 = `He is Johnny`;
var str3 = 'Good Morning "Tomy"';
var x = 125;
var y = x + 3.7;
var z= x + y;
Null:- Null has one value: null. It is explicitly nothing. A null value
means that there is no value. It is not equivalent to an empty string ("")
or 0, it is simply nothing.
var a = null;
Undefined:- The meaning of undefined is “value is not assigned”. If a
variable is declared, but not assigned, then its value is undefined:
var car;
Page 6
Array:- An array is a type of object used for storing multiple values in
single variable. Each value (also called an element) in an array has a
numeric position, known as its index, and it may contain data of any
data type-numbers, strings, booleans, functions, objects, and even other
arrays. The array index starts from 0, so that the first array element
is arr[0] not arr[1]. The simplest way to create an array is by specifying
the array elements as a comma-separated list enclosed by square
brackets, as shown in the example below:
var colors = ["Red", "Yellow", "Green", "Orange"];
var cities = ["London", "Paris", "New York"];
alert(colors[0]); // Output: Red
alert(cities[2]); // Output: New York
OPERATORS:
Arithmetic Operators
Arithmetic operators are used to perform arithmetic between variables and/or
values. Given that y=5, the table below explains the arithmetic operators:
Operator Description Example Result
+ Addition x=y+2 x=7 y=5
- Subtraction x=y-2 x=3 y=5
* Multiplication x=y*2 x=10 y=5
/ Division x=y/2 x=2.5 y=5
% Modulus (remainder) x=y%2 x=1 y=5
++ Increment x=++y x=6 y=6
x=y++ x=5 y=6
-- Decrement x=--y x=4 y=4
x=y-- x=5 y=4
Page 7
Assignment Operators
Assignment operators are used to assign values to JavaScript variables.
Given that x=10 and y=5, the table below explains the assignment operators:
Operator Example Same As Result
= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0
Page 8
>= is greater than or equal to x>=8 is false
<= is less than or equal to x<=8 is true
Logical Operators
Logical operators are used to determine the logic between variables or values.
Given that x=6 and y=3, the table below explains the logical operators:
Operator Description Example
&& And (x < 10 && y > 1) is true
|| Or (x==5 || y==5) is false
! Not !(x==y) is true
CONDITIONAL STATEMENTS
In JavaScript we have the following conditional statements:
if statement - use this statement to execute some code only if a
specified condition is true
if...else statement - use this statement to execute some code if the
condition is true and another code if the condition is false
if...else if....else statement - use this statement to select one of many
blocks of code to be executed
switch statement - use this statement to select one of many blocks of
code to be executed
If Statement
Use the if statement to execute some code only if a specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true
}
Note that if is written in lowercase letters. Using uppercase letters (IF) will
generate a JavaScript error!
Example
<script>
var myAge = 20;
var yourAge = 21;
Page 9
}
</script>
Notice that there is no ..Else.. in this syntax. We tell the browser to execute
some code only if the specified condition is true.
If...else Statement
Use the if....else statement to execute some code if a condition is true and
another code if the condition is not true.
Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}
Example
<script>
var myAge = 22;
var yourAge = 20;
Page
10
else
{
code to be executed if neither condition1 nor condition2 is true
}
Example
<script type="text/javascript">
var a = 10;
var b = 5;
if (a>b)
{
document.write("<b>a is larger than b</b>");
}
else if (a<b)
{
document.write("<b>b is larger than a</b>");
}
else
{
document.write("<b>a nd b are equal</b>");
}
</script>
Switch Statement
Use the switch statement to select one of many blocks of code to be executed.
Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}
This is how it works: First we have a single expression n (most often a variable),
that is evaluated once. The value of the expression is then compared with the
values for each case in the structure. If there is a match, the block of code
associated with that case is executed. Use break to prevent the code from
running into the next case automatically.
Page
11
Example
<script type = "text/javascript">
var grade = 'C';
switch (grade) {
case 'A':
document.write("Good job<br />");
break;
case 'B':
document.write("Pretty good<br />");
break;
case 'C':
document.write(" <br />");
break;
case 'D':
document.write("Not so good<br />");
break;
case 'F':
document.write("Failed<br />");
break;
default:
document.write("Unknown Grade<br />")
}
</script>
LOOPS
Loops execute a block of code a specified number of times, or while a
specified condition is true. Often when you write code, you want the same block
of code to run over and over again in a row. Instead of adding several almost
equal lines in a script we can use loops to perform a task like this. In
JavaScript, there are two different kind of loops:
for - loop through a block of code a specified number of times
while - loop through a block of code while a specified condition is true
do.…..while loop through a block of statement will execute at lease once
Page
12
Syntax
for (initialisation; condition_checkd; incre/decre)
{
code to be executed
}
For statement includes the following three important parts:
The loop initialization where we initialize our counter to a starting value.
The initialization statement is executed before the loop begins.
The test statement which will test if a given condition is true or not.
If the condition is true, then the code given inside the loop will be
executed, otherwise the control will come out of the loop.
The iteration statement where we can increase or decrease our counter.
We can put all the three parts in a single line separated by semicolons.
Example
<script>
for (i = 15; i <= 65; i++)
{
if(i%2==0)
{
document.write("     "+i);
}
}
</script>
Example
<script>
var i=15;
while (i <= 65)
{
if(i%2==0)
{
document.write("     "+i);
}
i=i+1;
}
</script>
Page
13
The do...while Loop
The do...while loop is a variant of the while loop. This loop will execute the
block of code ONCE, and then it will repeat the loop as long as the specified
condition is true. Don’t miss the semicolon after the while statement
Syntax
do
{
code to be executed
}
while (condition);
Example
<script>
var i=15;
do{
if(i%2==0)
{
document.write("     "+i);
}
i=i+1;
}
while (i <= 65) ;
Page
14
continue;
if (i === 11)
continue;
document.write("<br>The number is: "+i);
}
</script>
OUTPUT FUNCTIONS
Two output functions are used in JavaScript
Write() method outputs one or more values to the screen without a
newline character.
Writeln() method outputs one or more values to the screen with a
newline character.
Example
<html><body>
<p>Note that write() does NOT add a new line after each statement:</p>
<script type="text/javascript">
document.write("Hello World!");
document.write("Have a nice day!");
</script>
<p>Note that writeln() add a new line after each statement:</p>
<script type="text/javascript">
document.writeln("Hello World!");
document.writeln("Have a nice day!");
</script>
</body> </html>
POPUP BOXES
In JavaScript three types of popups used
1. alert() Box
2. confirm() Box
3. prompt() Box
Alert Box
An alert box is often used if we want to make sure information comes through
to the user. When an alert box pops up, the user will have to click "OK" to
proceed.
Syntax:
alert("sometext");
Example:
<html><head>
</head><body>
<h2>Alert Box Displayed</h2>
<script type="text/javascript">
Page
15
alert("Good Morning");
</script>
</body></html>
Confirm Box
A confirm box is often used if we want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or
"Cancel" to proceed. If the user clicks "OK", the box returns true. If the user
clicks "Cancel", the box returns false.
Syntax
confirm("sometext");
Example
<html><head>
</head>
<body>
<h2>Confirm Box Displayed</h2>
<script type="text/javascript">
confirm("Do You Wnats to Open This Document?");
</script>
</body>
</html>
Prompt Box
A prompt box is often used if we want the user to input a value before entering
a page. When a prompt box pops up, the user will have to click either "OK" or
"Cancel" to proceed after entering an input value. If the user clicks "OK" the
box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax
prompt("sometext","defaultvalue");
Example
<html><head>
</head>
<body>
<h2>Prompt Box Displayed</h2>
<script type="text/javascript">
var name;
name=prompt("Please enter your name","Harry Potter");
document.write(name);
</script>
</body>
</html>
Page
16
FUNCTIONS
There are two variant of functions
1. Built-in functions
2. User defined functions
isNan():- It determines whether a value is NaN or not. The NaN means Not- a-
Number. It checks the value is an illegal number. This function will returns
Boolean value. That is, it returns true if the value equates to NaN. Otherwise it
returns false.
Examle
isNan(123); //returns false
isNan(“hello”); //returns true
Syntax
parseInt(value, radix);
Page
17
enclosed within parenthesis and separated by comma. A list of statement
composing the body of the function enclosed within curly braces { }.
Function can be called (invoked) by typing its name followed by a set of
parenthesis. Function can return a value (result) back to the script using
return statement.
Syntax:-
function function_name(var1,var2,...,varX)
{
some codes;
}
The parameters var1, var2, etc. are variables or values passed into the
function. The { and the } defines the start and end of the function. A function
with no parameters must include the parentheses () after the function
name. Do not forget about the importance of capitals in JavaScript! The
word function must be written in lowercase letters, otherwise a JavaScript
error occurs! Also note that we must call a function with the exact same
capitals as in the function name.
Example
<html>
<head>
<script type="text/javascript">
function fact()
{
var n,f;
f=1;
n=prompt("Enter The Value");
for(i=1;i<=n;i++)
{
f = f * i;
}
document.write("the factorial of "+n+" is: "+f);
}
</script>
</head>
<body>
<script type="text/javascript">
fact();
</script>
</body>
</html>
Page
18
CALLING FUNCTIONS WITH TIMER
To execute a function after a certain period of time, we use setTimeout().
Its basic syntax is
setTimeout(function, milliseconds)
This function accepts two parameters: A function, which is the function to
execute. An optional delay parameter, in milliseconds
Example 1
<html>
<head>
<script type="text/javascript">
function fact()
{
var n,f;
f=1;
n=prompt("Enter The Value");
for(i=1;i<=n;i++)
{
f = f * i;
}
document.write("the factorial of "+n+" is: "+f);
}
</script>
</head>
<body>
<script type="text/javascript">
setTimeout(fact,5000);
</script>
</body>
</html>
Example 2
<html>
<head>
<script type="text/javascript">
function display()
{
alert("Good Morning");
}
Page
19
</script>
</head>
<body>
<script type="text/javascript">
setInterval(display,3000);
</script>
</body>
</html>
JAVASCRIPT EVENTS
By using JavaScript, we have the ability to create dynamic web pages.
Events are actions that can be detected by JavaScript. Every element on a web
page has certain events which can trigger a JavaScript.
onClick
We can use the onClick event of a button element to indicate that a
function will run when a user clicks on the button. We define the events in the
HTML tags. Execute a JavaScript when the user clicks on an element. Events
are normally used in combination with functions, and the function will not be
executed before the event occurs.
Example
<html> <head>
<script>
function display() {
alert("GEMS COLLEGE");
}
</script> </head>
<body>
<p>Click the following button and see result</p>
<form >
<input type="button" onclick="display()" value="Click Me" />
<h1 onclick="this.innerHTML='Ooops!'">Click on this text!</h1>
</form> </body><html>
onLoad
The onload event occurs immediately after a page is loaded. The
onLoad event is triggered when the user enters the web page. The onLoad event
is often used to check the visitor's browser type and browser version, and
load the proper version of the web page based on the information. The
onLoad event is also often used to deal with cookies that should be set when a
user enters a web page. For example, we could have a popup asking for the
user's name upon his first arrival to our page. The name is then stored in a
cookie. Next time the visitor arrives at our page; we could have another popup
saying something like: "Welcome John Doe!".
Page
20
Example
Alert "Page is loaded" immediately after a page is loaded:
<!DOCTYPE html>
<html><head>
<script>
function display() {
alert("Hello, Good Morning");
}
</script></head>
<body onLoad="display()">
<h1>Hello World!</h1>
</body></html>
onBlur()
It occurs when an object loses focus. The onblur event is most often
used with form validation code. When the user leaves a form field, it will occur.
The onblur event is the opposite of the onfocus event.
Example
<!DOCTYPE html>
<html><body>
Enter your name: <input type="text" id="fname" onblur="display()">
<h3>When the focus is lost, the input text converts into upper case.</h3>
<script>
function display() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
}
</script></body><html>
onChange
The onchange event occurs when the content of an element, the
selection, or the checked state have changed. The onchange event occurs
when the value of an element has been changed. For radio buttons and
checkboxes, the onchange event occurs when the checked state has been
changed. Only works on <input>, <textarea> and <select> elements.
Example
<!DOCTYPE html>
<html><body>
Enter your name: <input type="text" id="fname" onChange="display()">
<h3>When the focus is lost, the input text converts into upper case.</h3>
<script>
function display() {
var x = document.getElementById("fname");
x.value = x.value.toUpperCase();
Page
21
}
</script></body><html>
onSubmit
The onsubmit event occurs when the submit button in a form is
clicked. The onSubmit event is used to validate ALL form fields before
submitting it. Below is an example of how to use the onSubmit event. The
checkForm() function will be called when the user clicks the submit button in
the form. If the field values are not accepted, the submit should be cancelled.
The function checkForm() returns either true or false. If it returns true the
form will be submitted, otherwise the submit will be cancelled:
Example
<!DOCTYPE html>
<html><body>
<h3>When you submit the form, a function is triggered which alerts some
text.</h3>
<form action="server.php" onsubmit="display()">
Enter name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form><script>
function display() {
alert("The form was submitted Sucessfully.....");
}
</script></body><html>
Page
22
representation of the web page, which can be modified with a scripting
language such as JavaScript.
String Object
A string is a sequence of letters, numbers, special characters or
combination of all. It is a global object is used to store strings. A string can be
any text inside double or single quotes:
String Property
Length:- Returns the length of a string
The following table lists the standard methods of the String object.
Method Description
big() Display text as if in a <big> element
bold() Display text as if in a <bold> element
charAt() Returns the character at the specified index.
concat() Joins two or more strings, and returns a new string.
indexOf() Returns the index of the first occurrence of the specified
value in a string.
italics() Display text as if in a <i> element
Page
23
search() Searches a string against a regular expression, and returns
the index of the first match.
slice() Extracts a portion of a string and returns it as a new string.
split() Splits a string into an array of substrings.
substr() Extracts the part of a string between the start index and a
number of characters after it.
substring() Extracts the part of a string between the start and end
indexes.
toLowerCase() Converts a string to lowercase letters.
toString() Returns a string representing the specified object.
toUpperCase() Converts a string to uppercase letters.
trim() Removes whitespace from both ends of a string.
Example
<html><body>
<h2>The length property returns the length of a string:</h2>
<p></p>
<p id="demo"></p>
<script type="text/javascript">
var str="Hello, Good Morning to All, Have a Nice Day!<br>";
document.write(str);
document.write("<BR>The length is: <BR> " +str.length);
var pos = str.indexOf("Morning");
document.write("<br>The position of Morning is:");
document.write("<br>"+pos);
var up=str.toUpperCase();
document.write(up);
var lw=str.toLowerCase();
document.write(lw);
var sub=str.substring(15,30);
document.write(sub);
</script></body><html>
Date Object
The Date object is a datatype built into the JavaScript. The date objects
are created with the new Date() constructor. By default, JavaScript will use
the browser's time zone and display a date as a full text string:
Most methods simply allow us to get and set the year, month, day, hour,
minute, second, and millisecond fields of the object.
There are 4 ways to create a new date object:
Page
24
new Date()
new Date(milliseconds)
new Date(date string)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
Method 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.
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.
Method Description
setDate() It sets the day value for the specified date on the basis of
local time.
setDay() It sets the particular day of the week on the basis of local
time.
setFullYears() It sets the year value for the specified date on the basis of
local time.
setHours() It sets the hour value for the specified date on the basis of
local time.
setMilliseconds() It sets the millisecond value for the specified date on the
basis of local time.
setMinutes() It sets the minute value for the specified date on the basis
of local time.
setMonth() It sets the month value for the specified date on the basis
of local time.
setSeconds() It sets the second value for the specified date on the basis
of local time.
toString() It returns the date in the form of string.
Page
25
Example
<!DOCTYPE html>
<html> <body>
<h2>Date() Object</h2>
<p id="demo"></p>
<script>
var d = new Date();
document.write(d);
var d1 = new Date(2018, 11, 24, 10, 33, 30, 38);
document.getElementById("demo").innerHTML = d1;
var d2 = new Date(2018, 11, 24);
document.write("<br><br>"+d2);
var d = new Date();
document.write("The current Year is: "+d.getFullYear());
document.write("<br>The current Month is: "+d.getMonth());
document.write("<br>The current Date is: "+d.getDate());
document.write("<br>The current Hours is: "+d.getHours());
document.write("<br>The current Minute is: "+d.getMinutes());
document.write("<br>The current Second is: "+d.getSeconds());
document.write("<br>The current Milliseconds is: "+d.getMilliseconds());
document.write("<br>The current Day is: "+d.getDay());
</script></body><html>
Array Object
An array is a type of object used for storing multiple values in a single
variable. A fixed-size sequential collection of elements of the same type. Each
value in an array has a numeric position, called index. The array index starts
from zero (0)
var cars = [“Hyundai", "Volvo", "BMW"];
Method Description
concat() Merge two or more arrays, and returns a new array.
findIndex() Returns the index of the first element in an array that pass
the test in a testing function.
join() Joins all elements of an array into a string.
pop() Removes the last element from an array, and returns that
element.
push() Adds one or more elements to the end of an array, and
returns the array's new length.
reverse() Reverses the order of the elements in an array.
slice() Selects a part of an array, and returns the new array.
sort() Sorts the elements of an array.
toString() Converts an array to a string, and returns the result.
Page
26
Example
<!DOCTYPE html>
<html><body>
<h3>Array Object </h3>
<p id="demo"></p>
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var fname=["Raju", "Kumar", "Babu", "Arjun","Lakshmi", "Divya"];
document.write("<br>"+fruits.toString());
document.write("<br>The No. of elements in array is: "+fruits.length);
document.write("<br>The deleted element is: "+fruits.pop());
document.write("<br>"+fruits.toString());
document.write("<br>Now No. of elements in array is: "+fruits.length);
document.write("<br>Adding two elements");
fruits.push("Grape","Chicku");
document.write("<br>"+fruits.toString());
document.write("<br>Now No. of elements in array is: "+fruits.length);
document.write("<br>Reverseof the array is: "+fruits.reverse());
document.write("<br>"+fruits.toString());
document.write("<br>Sorted array is: "+fruits.sort());
document.write("<br>"+fruits.toString());
</script></body></html>
Page
27