7 JavaScript
7 JavaScript
JAVAScript
A scripting or script language is a programming language that supports scripts — programs written for a
special run-time environment that automates the execution of tasks that could alternatively be executed one-
by-one by a human operator.
In general scripting languages are used in small doses, for specific tasks. Such simple tasks illustrate basic
features of the scripting language.
1) JavaScript
JavaScript is a object–based scripting language developed by Netscape, to support the development of both
client and server components of web–based applications. On the client side it can be used to write programs
that are executed by a web browser within the context of web page. On the server side it can be used to write
web server programs that can process information submitted by a web browser and then updates browser’s
display accordingly.
JavaScript can update and change both HTML and CSS. 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. JavaScript is a purely interpreted language.
Features of Javascript
It is an interpreted language, embedded within HTML pages
Minimal Syntax- Easy to learn
Supports quick development and better performance
Designed for programming user events
Platform Independent / Architecture Neutral
Javascript Capabilities
Improve the user interface of a website
Make your site easier to navigate
Easily create pop-up alert, windows
Replace images on a page without reload the page
Event handling and Form validations
K. L. Narayana 1
JAVAScript
2) Difference between client side and server side scripting:
Client Side Scripting Server Side Scripting
It runs on client machine i.e. web browser It runs on web server
Source code is visible to users Source code is not visible to users
Response from a client-side script is faster becasue the Response from a server-side script is slower
scripts are processed on the local computer. because the scripts are processed on the remote
computer.
Create control event procedures Access server resources such as databases and hide
business logic implementation
It is used for dynamic related functions. It is used for database specific functions
Examples: Javascript, VB script, Examples: PHP, JSP, ASP, ASP.Net, Ruby, Perl
ECMA(European Computer Manufacturers and many more.
Association) Script etc.
JAVASCRIPT JAVA
JavaScript code run on browser only. Java creates application that can run in a virtual
machine or browser.
Local: JavaScript is embedded into Remote: Java Applet code is form a remote system.
downloaded HTML documents.
Interpreted: Interpreted by the client-side Compiled: Compiled on the server before executed on
computer. the client machine.
Object–Based: Uses built–in, extensible Object–oriented: Supports all features of OOPS.
objects, but no classes or inheritance. Applets consist of object classes with inheritance.
Loosely Typed: Variable can hold any type Strongly Typed: Variables can hold only one type of
of value. value.
JavaScript is text based dynamic and weakly Java is high-level, static,compiled and strongly typed
typed language. language.
Javascript source code visible to user. Java Applet code is not visible to user.
This tag can be used one or multiple times in the <head> as well as in the <body> element. Because HTML
pages are read sequentially, a lot of scripting code may appear in the head section of a document. All Java
Script functions should be written in head tag.
Attributes of Script
LANGUAGE:
It specifies the scripting language of the script. Possible values are JavaScript and VbScript.
SRC:
This attribute is used to indicate the URL of a file that contains an external script to load. Possible value is
URL. Specifies the location of an external script (Ex: .JS file).
TYPE:
Indicates the MIME type of the script to run. Possible value is text/JavaScript and text/VbScript.
2 K. L. Narayana
JAVAScript
MIME Types:
MIME stands for Multipurpose Internet Mail Extensions. It's a way of identifying files on the Internet
according to their nature and format. It consists of a type and a subtype, two strings, separated by a '/'.
Type Description Example of typical subtypes
Represents any document that contains text text/plain, text/html, text/css, text/javascript
Text
and is theoretically human readable
Represents any kind of images. Videos are not image/gif, image/png, image/jpeg,
Image included, though animated images (like animated image/bmp
gif) are described with an image type.
audio/midi, audio/mpeg, audio/webm,
Audio Represents any kind of audio files
audio/wav
Video Represents any kind of video files video/webm, video/ogg
application Represents any kind of binary data. application/pdf, application/xml,
Example1.html
<html> <head> <title>JAVASCRIPT Tutorials </title>
<SCRIPT>document.write("<h3>This is my first JavaScript Program</h3>")</SCRIPT>
</head><BODY>
<script>
document.write("<font color=red size=5> Welcome to the Web Designing </font>")
window.alert("Welcome to the World of Interactive Scripting")
</script></BODY></html>
Output:
Identifiers
An identifier in JavaScript is a name used to refer to a variable or function name. The first character must be
an alphabet (lowercase or uppercase) or an underscore (_). Subsequent characters may be any number of
alpha numeric or an underscore. Special character are not allowed except dollar sign $
Variables:
The value associated with a name need not be constant; new values may be assigned to existing names.
Since the value associated with a name may vary, the names are called variables.
For example, the following line of JavaScript assigns the value 2 to a variable named i.
i = 2;
And the following line adds 3 to i and assigns the result to a new variable sum:
sum = i + 3;
K. L. Narayana 3
JAVAScript
Variable Declaration
Declaring a variable type is not required, but it is good programming style to declare variables before
using them.
And you can combine variable declaration with initial assignment to the variable:
var i = 2;
Untyped Variables
Variables in JavaScript can hold values of any data type, so it is known as untyped variables.
For example, it is perfectly legal in JavaScript to assign a number to a variable and later assign a string to it:
x = 10;
x = "KLN"; // JavaScript allows the same variable to contain different types of data values.
Data Types
Primitive data types
Number: integer & floating-point numbers
Boolean: logical values “true” or “false”
String: a sequence of alphanumeric characters
Composite data types (or Complex data types)
Object: a named collection of data
Array: a sequence of values
Special data types
null: an initial value is assigned
undefined: the variable has been created but not yet assigned any value
Numbers
Numeric literals can be integer or floating-point, and integers can be expressed in decimal, octal, or
hexadecimal notation. All numbers in JavaScript are represented as floating-point values.
Integer literals
Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8). A leading 0 (zero)
on an integer literal indicates it is in octal; a leading 0x (or 0X) indicates hexadecimal.
Floating–Point Literals
Floating–point can have the following parts: an integer, a decimal point ("."), a fraction (another decimal
number), an exponent part ("e" or "E") followed by an integer, which can be signed ("+" or "–"). A floating–
point literal must have at least one digit, plus either a decimal point or "e" (or "E").
Boolean Literals
A Boolean value is a logical value of either true or false.
Often used in decision making and data comparison.
4 K. L. Narayana
JAVAScript
JavaScript operators:
Assignment operators
Arithmetic operators
Comparison operators
Bitwise operators
Logical operators
String operators
Conditional (ternary) operator
Comma operator
Unary operators
Relational operator
Type of Operator
In addition to these basic arithmetic operations, JavaScript supports more complex mathematical operations
through a large number of mathematical functions with Math object, so we use always use the literal name
Math to access them.
Example2:
<html> <BODY><script>
r=120; var a=Math.sin(r)
x=4; y=3; b = Math.sqrt(x*x + y*y);
document.write("<h2>Value of a = " + a +
"</h2>")
document.write("<h1>Value of b = " + b +
"</h1>")
</script></BODY></html>
+ Concatenate Operator
The + operator concatenates two strings. That is, it creates a new string that consists of the first string
followed by the second. Thus, for example, the following expression evaluates to the string "hello there":
"hello" + " " + "there". In javascript string can be kept in single or double quotes.
Example3:
<html> <BODY> <script>
a = "Engineering"; c=" "; b="College";
x = a + c + b; // here x value is "Engineering
College"
document.write("<font color=red size=6>" + x)
</script></BODY></html>
K. L. Narayana 5
JAVAScript
Example4:
<html> <body> <script>
a=25; b="25"
x="BBSR"; y='BBSR'
z="BBS"
document.write("<font color=red size=6>")
document.write(" a==b " + (a==b) + "<p>")
document.write(" a===b " + (a===b) + "<p>")
document.write(" x==y " + (x==y) + "<p>")
document.write(" x===y " + (x===y) + "<br>")
document.write(" x===z " + (x===z) + "<br>")
</script> </body> </html>
Possible values are "number", "string", "boolean", "object", "function", and "undefined" for undefined
values. Both arrays and objects return the "object" value.
The typeof operator returns a string indicating the type of the unevaluated operand. operand is the string,
variable, keyword, or object for which the type is to be returned.
var myFun = new Function("5+2") // typeof(myFun) is object
var shape="circle" // typeof shape is string
var size=1 // typeof(size) is number
var today=new Date() // typeof today is object
var BPUT; // typeof BPUT is undefined
For property values, the typeof operator returns the type of value the property contains:
typeof document.lastModified is string
typeof window.length is number
For methods and functions, the typeof operator returns results as follows:
typeof eval is function
typeof parseInt is function
Syntax:
new constructor
The new operator works as follows: first, it creates a new object with no properties defined. Next, it invokes
the specified constructor function, passing the specified arguments, and passing the newly created object as
the value of the this keyword.
6 K. L. Narayana
JAVAScript
Null
The JavaScript keyword null is a special value that indicates "no value." Technically speaking, null is a
value of object type, so when a variable holds the value null, you know that it does not contain a valid object
or array. Null refers to “nothing”. You can declare and define a variable as “null” if you want absolutely
nothing in it.
For Example
var branch=null
Undefined
There is another special value occasionally used by JavaScript. This is the "undefined" value returned when
you use a variable that doesn't exist, or a variable that has been declared, but never had a value assigned to it.
There is no undefined keyword for the undefined value. The undefined value is not the same as null.
An “undefined” value is returned when you attempt to use a variable that has not been defined or you have
declared but you forgot to provide with a value.
Example5.html
<html><body> <script language="javascript"> Output:
var str = "29.12"; num = parseInt(str)
fnum = parseFloat(str)
College=null
document.write("<font size=5>str " + str + " is of type " + typeof(str))
document.write ("<br>num " + num + " is of type " + typeof(num))
document.write ("<br>fnum " + fnum + " is of type " + typeof(fnum))
document.write ("<br> parseInt is of type " + typeof(parseInt));
document.write ("<br> Date is of type " + typeof(new Date()));
document.write ("<br> BPUT is " + typeof(BPUT));
document.write ("<br> College is " + typeof(College));
document.write ("<br> Value of College is " + College);
</script></body></html>
The if Statement
The if statement is the "control statement" that allows to "make decisions," or to execute statements
conditionally.
In the first form, the expression is true, then statement is executed. If the expression is false, then statement
is not executed.
if (expression)
statement1
else
statement2
In the second form of the statement, the expression is evaluated, and if it is true, then statement1 is executed;
otherwise statement2 is executed.
K. L. Narayana 7
JAVAScript
The switch statement
Allows you to merge several evaluation tests of the same variable into a single block of statements.
Example6.html
<html> <script language="JavaScript">
var chr;
chr = prompt("Pls enter any character.");
switch(chr)
{ case 'a' : case 'e' : case 'i' : case 'o' : case 'u' : alert("Vowel"); break;
case 'A' : case 'E' : case 'I' : case 'O' : case 'U' : alert("Vowel"); break;
default : alert("CONSONANT");
}
</script> </html>
Output:
Syntax:
while (Expression)
{ statements;
counter increment/decrement;
}
Syntax:
do
{ statements;
counter increment/decrement;
} while (termination condition)
For example:
for(i = 0, j = 10 ; i < 10 ; i++, j--)
sum += i * j;
8 K. L. Narayana
JAVAScript
Example7.html
<html> <body> <h1> Enter your Date of Birth </h1> Output:
<table><tr> <th><font size=3>Date of Birth: </font>
<th><Select name=Date>
<option>DD<script>
for(i=1; i<=31;i++)
document.write("<option>" + i);
</script>
<th><Select name=Month><option>MM<script>
for(i=1; i<=12;i++)
document.write("<option>" + i);
</script><th><Select
name=Year><option>YYYY<script>
for(i=1901; i<=2020;i++)
document.write("<option>" + i);
</script> </table> </body> </html>
syntax:
for (variable in object)
statement
The variable should be the name of a variable, or should be an element of an array or a property of an
object.
The for..in statement provides a way to loop through the properties of an object. The body of the for..in loop
is executed once for each property of object. Before the body of the loop is executed, the name of one of the
object's properties is assigned to variable, as a string. Within the body of the loop, you can use this variable
to look up the value of the object's property with the [ ] operator.
Example8.html
<html> <script language="JavaScript">
var book=" ";
var booklist = new Array("Chinese", "English", "Japaneese");
for (var counter in booklist) {
book += booklist[counter] + " ";
}
alert(book); </script> </html>
with statement
The with statement establishes the default object for a set of statements.
syntax:
with (object)
statement
The above with statement specifies that the Math object is the default object. The statements following the
with statement refer to the PI property and the cos and sin methods, without specifying an object. JavaScript
assumes the Math object for these references.
K. L. Narayana 9
JAVAScript
Example9:
<html> <body> <script> Output:
var a, x, y, z, r=5
with(Math)
{ a=PI * r * r
x=pow(r,2)
y=sqrt(x); z=max(x,y);
}
document.write("<font color=red size=6> Area = "
+a)
document.write("<p> x = " + x)
document.write("<p> y = " + y)
document.write("<p> Max Value = " + z)
</script> </body> </html>
Similarly, instead of calling document.write() over and over again in a JavaScript program, you could use a
with(document) statement, and then invoke write() simply.
Example10:
<html> Output:
<body> <script>
with(document)
{ write("<font size=5>" + "Welcome to JAVAScript by KLN")
write("<p>" + "Design the Interactive Web Pages...")
write("<p>" + "By using HTML5, CSS3, XML, AJAX and Php")
}
document.write("<p>Besto of Luck")
</script>
</body> </html>
6) Functions
A function is a piece of code that is defined once in a program and can be executed many times by the
program. JavaScript functions can be passed arguments or parameters that specify the value or values that
the function is to operate upon, and can return values. Functions in JavaScript are closely integrated with
JavaScript objects.
Function syntax:
function funcname ([arg1 [,arg2 [..., argn]]])
{
statements //Function Body
}
return
When the return statement is executed, the expression is evaluated, and returned as the value of the function.
The return statement can be used to return a value like this:
10 K. L. Narayana
JAVAScript
Syntax:
function square(x)
{ return x*x;
}
The return statement may also be used without an expression to simply terminate execution of the function
without returning a value. It is a syntax error to use the return statement anywhere except in a function body.
Recursive Function
function factorial(x)
{ if (x <= 1)
return 1;
else
return x * factorial(x-1);
}
y = square(x);
Since JavaScript is an untyped language, you are not expected to specify a data type for function arguments.
Example11:
<!-- Generally Function defined in head --> Output:
<html> <head> <script>
function fact(num)
{ var f=1;
for(i=num; i>0; i--)
f = f *i;
document.write("<h2>Factorial of " + num + " = " + f)
}
</script> </head> <body> <script>
fact(5); fact(8)
</script> </body> </html>
Example12:
<!-- Generally Function defined in head --> Output:
<html> <head> <script>
function factorial(x)
{ if (x ==0)
return 1;
else
return x * factorial(x-1);
}
</script> </head> <body> <script>
var x=4, y=6
document.write("<h2>Factorial of " + x + " = " +
factorial(x)); z=factorial(y);
document.write("<h2>Factorial of " + y + " = " + z)
</script> </body> </html>
K. L. Narayana 11
JAVAScript
7) Built-in Functions
JavaScript provides several built-in functions for manipulating string and numeric values:
parseInt converts a string to an integer of the specified radix (base), if possible.
parseFloat converts a string to a floating–point number, if possible.
eval attempts to evaluate a string representing any JavaScript literals or variables, converting it to a number.
function add()
{ document.fr1.output.value=parseInt(fr1.inputA.value)+parseInt(fr1.inputB.value);
}
function sub()
{ document.fr1.output.value= parseInt(fr1.inputA.value)-parseInt(fr1.inputB.value);
}
Here the var x will get the result, namely, "true" or "false". Then we use a "if else" statement to give the
script the ability to choose between two paths, depending on its value.
Prompt is used to allow a user to enter something, and do something with that info:
var n=window.prompt("please enter your name")
window.alert(n)
The prompt will store whatever the user typed in the prompt box, using n. Then display it.
Example15.html
<html> <body bgcolor=cyan><div align=center>
<h3>Window Properties alert, confirm, and prompt </h3>
<div align=center> <form>
<input type="Button" value="Ok Button" onclick="window.alert('Welcome to KLN JAVAScript')" >
<input type="Button" value="Ok & Cancel Button"
onclick="window.confirm('Are you want more Examples')" >
<input type="Button" value="Input Value" onclick="window.prompt('Enter your Gmail-ID :: ')">
</form> </div>
</body></html>
K. L. Narayana 13
JAVAScript
Output:
9) Object Hieratchy
Objects
An object is a data type that contains named pieces of data. An Object in context of JavaScript, can be
defined as collection of methods and properties consisting of a set of definable characteristics that one can
view or modify.
Every object is unique in some way. Three important facets of an object are what it looks like, how it
behaves, and how scripts control it. Those three facets are Properties, Methods and Event Handlers.
Properties
Every object has properties. To access a property, use the object name followed by a period and the property
name. Any physical object you hold in your hand has a collection of characteristics that defines it’s each of
those features is called a property.
To gain access to an object’s property, you use the hierarchical dot syntax scheme.
Document.formName.clicker.name
Document.formName.clicker.value
14 K. L. Narayana
JAVAScript
Methods
Object’s methods are called functions and its data are called its properties.
For Example:
Doucmnet.write(“Welcome to JAVA Script”);
Creating an Arrays
There is a predefined Array() constructor function that you can use to create arrays. You can use this
constructor in three distinct ways. The first is to call it with no arguments:
var a = new Array();
This method creates an empty array with no elements. It is like calling new Object(), except that it gives the
newly created object (i.e., an array) a length property set to 0.
The second technique is to call the Array() constructor with a specified length:
a = new Array(10);
The final technique allows you to specify values for the first n elements of an array:
a = new Array(56, "Ram Kumar", 78);
In this form, the constructor is passed two or more arguments. Each argument specifies an element value and
may be of any type. Elements are assigned to the array starting with element 0. The length property of the
array is set to the number of arguments that were passed to the constructor.
Methods of an Array
concat Joins two arrays and returns a new array.
join Joins all elements of an array into a String.
pop Removes the last elements from an array and returns that element.
push Ads one or more elements to the end of an array and returns that last element added.
reverse Transposes the elements of an array: the first array element becomes the last and the last
becomes the first.
shift Removes the first element from an array and returns that element.
slice Extracts a section of an array and returns a new array.
splice Adds and/or remives elements form an array.
sort Sorts the elements of an array.
tostring Returns a string representing the specified object.
unshift Adds one or more elements to the front of an array and returns the new length of the array.
K. L. Narayana 15
JAVAScript
Array Methods
The Array.join() method converts all the elements of the array to a string, and concatenates them,
separating them with an optionally specified string passed as an argument to the method. If no separator
string is specified, then a comma is used. For example, the following lines of code produce the string
"1,2,3":
And the following lines specify the optional separator to produce a slightly different result:
a = new Array(1,2,3);
s = a.join(", "); // s == "1, 2, 3". Note the space after the comma.
The Array.reverse() method reverses the order of the elements of an array. It does this "in place"--i.e., it
doesn't create a new array with the elements rearranged, but instead rearranges them in the already existing
array. For example, the following code, which uses the reverse() and the join() methods, produces the string
"3,2,1":
The Array.sort() method, which sorts the elements of an array. Like the reverse() method, it does this "in
place". When sort() is called with no arguments, it sorts the array elements in alphabetical order (temporarily
converting them to strings, to perform the comparison, if necessary):
Output:
16 K. L. Narayana
JAVAScript
Example17: Stack using Array
<html> <script>
function Stack()
{ this.stac=new Array();
this.pop=function()
{ return this.stac.pop();
}
this.push=function(item)
{ this.stac.push(item);
}
}
var stack=new Stack();
stack.push("Atul"); stack.push("Amit"); stack.push("Suraj");
stack.push("Ankita"); stack.push("Anaya"); stack.push("Nayan");
alert("Thank You " + stack.pop());
alert("Thank You " + stack.pop());
alert("Thank You " + stack.pop());
alert("Thank You " + stack.pop());
</script> </html>
The first square bracket references the desired element in the outer array. The second square bracket
references the desired element in the inner array. JavaScript array indexes start at zero.
You can apply array methods to the nested arrays. Here we use the push method to add two new elements to
the second sub-array:
ar[2].push(“TIFAC”, “CORE”);
Document Object
Properties alinkColor, applet, area, bgColor, cookie, domain, fgColor, form, forms, Image,
lastModified, linkColor, Link, title, URL, vlinkColor.
Methods close, open, write, writeln.
Document.title Property:
Not every property about a document is set in a <body> tag attribute. If you assign a title to the page in the
<title> tag set within the head portion, that title text is reflected by the document.title property.
18 K. L. Narayana
JAVAScript
Document.write( ) Method:
The document.write( ) method can be used in both immediate scripts to create content in a page as it loads
and in deferred scripts that create new content in the same or different window. The method requires one
string parameter, which is the HTML content to write to the window or frame. Such string parameters can be
variables or any other expressions that evaluate to a string. Very often, the content being written includes
HTML tags.
Example20.html
<html> <head><title>This is an example of Java Script page</title> </head>
<body bgcolor=cyan text=red><h2>Welcome to the JavaScript course!</h2>
<script language="JavaScript">
var a=document.bgColor
var b=document.lastModified
var c=document.fgColor
document.write("<h1><small>Your Course Instructor is</small> Mr. KLN </h1>")
document.write("<h4>Background colour of the Browser : "+a)
document.write("<br>Last modified date of the Document : "+b)
document.write("<br>Foreground colour of the Browser : "+c)
</script> </body></html>
Output:
Example21.html
<html> <script>
document.write("<font size=5 color=red>",navigator.appName, "</font><br>")
document.write(navigator.appCodeName, "<br>")
document.write(navigator.appVersion, "<br>")
document.write(navigator.javaEnabled(), "<br>")
</script> </html>
Output:
K. L. Narayana 19
JAVAScript
14) String Object
JavaScript does not have a string data type. However, you can use the String object to work with strings.
For Example:
instructor = new String("Lakshmi Narayana")
var coll="National Institute of Science & Technology"
Operators:
The “+” operator will concatenate the two strings.
var msg1 = "Hello"; var msg2 = "World"
var msg = msg1 + " " + msg2 //msg="Hello World"
length property:
var len = “Hell World”.length //len=10
String Methods
charAt(position):
The charAt method returns the character at the specified position in string.
var x=“mango”.charAt(1) //x=“a”
indexOf(Str [, startIndex]):
Returns the index of the first occurrence of the search string (Str).
var y=“banana”.indexOf(“a”) //x=1
var y=“banana”.indexOf(“a”,2) //x=3
lastIndexOf(Str [, startIndex]):
Returns the index of the last occurrence of the search string (Str).
var y=“banana”.lastindexOf(“a”) //x=5
var y=“banana”.indexOf(“a”,2) //x=3
substr(start [, len]):
Returns a substring within a string .
var str1=“Kolkata”.substr(0,4) //str1=“Kolk”
substring(sart, end):
The substring method takes two arguments and returns a subset of the string between the two arguments.
var str1="Kolkata".substring(2,5) //str1="lka"
toUpperCase():
var upstr =“hello”.toUpperCase() // upstr=“HELLO”
toLowerCase():
var lowstr =“HELLO”.toLowerCase() // lowstr=“hello”
20 K. L. Narayana
JAVAScript
Example22.html (Lower case to uppercase Convesion Program)
<html> <head><title>Lower case to uppercase Convesion Program</title> <script>
function upper()
{ document.converter.input.value=document.converter.input.value.toUpperCase()
}
</script> </head><body bgcolor=slate text=cyan>
<h2 align=center> Enter Lower case Letters for Conversion to Uppercase
<form name=converter><br>Enter name in Lowercase :
<input type=text name=input value=" " size=50 onChange="upper()"> </h2>
<font color=red size=5> After Entering Your Name Press TAB </font> </form></body></html>
Example23.html
<html><body><script>
var name="K. Lakshmi Narayana"
document.write("<p>" + name.bold())
document.write("<p>" + name.italics())
document.write("<p>" + name.strike())
</script></body></html>
Properies of Math
Name Description
E Returns the mathematical constant E, the base of natural logarithms, approximately 2.718.
LOG10E Returns the base 10 logarithm of E (approximately equal to 0.434).
LOG2E Returns the base 2 logarithm of E (approximately equal to 1.442).
PI Returns the ratio of the circumference of a circle to its diameter ( approximately 3.14159).
SQRT1_2 Returns the square root of 1/2 i.e. 0.5, approximately 0.707.
SQRT2 Returns the square root of 2 (approximately 1.414).
K. L. Narayana 21
JAVAScript
Methods of Math
Method Description
abs Absolute value
sin, cos, tan Standard trigonometric functions; argument in radians
acos, asin, atan Inverse trigonometric functions; return values in radians
exp, log Exponential and natural logarithm, base e
ceil Returns least integer greater than or equal to argument
floor Returns greatest integer less than or equal to argument
min, max Returns greater or lesser (respectively) of two arguments
pow Exponential; first argument is base, second is exponent
round Rounds argument to nearest integer
sqrt Square root
where dateObjectName is the name of the Date object being created; it can be a new object or a property of
an existing object.
22 K. L. Narayana
JAVAScript
Example25.html (Display the date in dd/mm/yyyy format)
<html><script>
var today_date= new Date()
var myyear=today_date.getFullYear()
var mymonth=today_date.getMonth()+1
var mytoday=today_date.getDate()
document.write(" <font color=red size=6>Today is Christmas : ")
document.write(+mytoday+"/"+mymonth+"/"+myyear+"</font>")
document.write("<h1>Wish You have a Good Luck and Bright Feature.<h1>")
document.write("<h3>Default Date Format is: "+today_date+"</h3>")
</script></html>
Output:
function checkTime(i)
{
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
</script> </head>
<body onload="startTime()">
<div id="txt"></div>
</body></html>
Output:
K. L. Narayana 23
JAVAScript
Window Object Methods:
Open( ) and close( ): Opens and closes a browser window; you can specify the size of the window, its
content, and whether it has a button bar, location field, and other "chrome" attributes.
alert( ): Displays an Alert dialog box with a message.
confirm( ): Displays a Confirm dialog box with OK and Cancel buttons.
prompt( ): Displays a Prompt dialog box with a text field for entering a value.
blur( ): Removes focus from a window.
focus( ): Gives focus to a window.
setTimeout( ): Evaluates an expression after the specified time.
print( ): Prints the contents of the window.
resizeBy( ): Resizes an entire eindow by moing the window’s bottom–right corner by the specified amount.
Syntax:
resizeBy(horizontal, vertical)
Horizontal: The number of pixels by which to resize the window horizontally.
Vertical: The number of pixels by which to resize the window vertically.
To make the current window 5 pixels narrow and 10 pixels taller than its curent dimensions, use this statement:
self.resizeBy(–5, 10) // Relativ ePositioning
You can refer to the properties, methods, and event handlers of the current window or another window (if
the other window is named) using any of the following methods:
self or current window: self and window are synonyms for the current window, and you can use
them optionally to refer to the current window.
top or parent: top and parent are also synonyms that you can use in place of the window name. top
refers to the topmost Navigator window, and parent refers to a window containing a frameset.
name of a window variable: The window variable is the variable specified when a window is
opened. For example, msgWindow.close() closes a window called msgWindow.
For example
<input type="button" value="Click here" onClick="window.open('www.nist.edu')">
You can also include the name and attributes to the open() method.
open("URL","name","attributes")
24 K. L. Narayana
JAVAScript
Example27.html
<HTML><HEAD><TITLE> Prize Winners </TITLE>
<SCRIPT>
var bGrounds=new Array("Green","red","Blue","Yellow","Lime");
var thisBG=0;
var bgColorCount=5;
function rotateBG()
{ if(document.images)
{ thisBG++;
if(thisBG == bgColorCount)
thisBG=0;
document.bgColor=bGrounds[thisBG];
setTimeout("rotateBG()", 700);
}
}
</SCRIPT> </HEAD> <BODY BGCOLOR="blue" onLoad="rotateBG()">
<div align=center><font color=maroon size=7>Congratulations!!!!!!!!!! <br>
<font color=yellow size=6>You Won the Scholarship. . . . . <br>
<!Assume that in the parent directory we have a images directory on that car.jpg is available>
<img src="../images/flag.jpg"> </div> <font color=red size=7 face=impact>
<marquee behavior=alternate>nist.edu</marquee> </font>
</BODY></HTML>
Output
Example28.html
<html><body><form> <font color=red size=6> bput.ac.in Registration Form. . .</font>
<p><big>Enter your E–mail ID :</big> <input type="text"> </p>
<p><big>Enter your password : </big>
<input type="password" name="My Password" size="20" maxlenngth="15"></p>
<p align=center> <input type=button value=LOGIN onclick="window.open('Example24.html')">
<input type="reset" value=CANCEL>
</form></body></html>
Output:
Window.status property
The window bar at the bottom of the browser window normally displays the URL of link when you roll the
mouse pointer on it. Here we can display the status of the window.
K. L. Narayana 25
JAVAScript
Example29.html
<html><head><script>
function showStatus(msg)
{ window.status = msg
return true
}
</SCRIPT></HEAD><BODY>
<h1> Move your mouse pointer on the below Links and saw the status BAR </h1>
<a href="www.yahoo.com" onMouseOut="return showStatus('chating with yahoo')">
yahoo mail</a>
<A HREF="www.nist.edu" onMouseOver = "return showStatus('nist.edu')"
onMouseOut="return showStatus('Thank you for visiting our Web Site')">
NIST Website</a> </body></html>
Output:
Example31.html Load a page in the Different window by using open() and close() Methods
<html><head> <script>
var newWindow
function makeWindow()
{ newWindow = window.open("","","status, height=200,width=400")
}
function reWrite()
{ if(newWindow.closed)
{ makeWindow();
}
26 K. L. Narayana
JAVAScript
var newcontent= "<HTML><BODY bgcolor=cyan><h1>Wish You have a Good Luck!"
newcontent +="<h3>It's from Lakshmi Narayana K. "
newcontent +="</body></html>"
newWindow.document.write(newcontent);
newWindow.document.close();
}
</script></head><body onLoad=makeWindow()><div align=center>
<h1> Example of docuemnt.write on Another Window </h1>
<form><input type=button value="Replace Content" onClick=reWrite()>
</div></form></body></html>
Output:
Example32.html Open a new HTML page in a new window by using open() and close() Methods
<html><head>
<script>
var newwindow
function windowopen( )
{ newwindow = window.open("Example24.html","new", "HEIGHT=350, WIDTH=400")
}
function windowclose( )
{ newwindow.close()
}
</SCRIPT>
</HEAD><BODY>
<FORM><font color=red size=6> Web Designing Tutorials. . . . .
<br> HTML, JavaScript, and FlashMx. . . . . </font>
<div align=right>
<INPUT TYPE="Button" onClick="windowopen()" value=" OPEN Tutorials " ><br>
<INPUT TYPE="Button" onClick="windowclose()" value="CLOSE Tutorials"></div>
</font> </form></body></html>
Output:
K. L. Narayana 27
JAVAScript
18) Event Handlers
Events are actions that take place in a document, usually as the result of user activity. Script code could be
added to HTML documents through special attributes called event handlers.
Examples of events include a user clicking a button, presenting a key, moving a window, or even simply
moving the mouse around the screen.
For example:
onClick="alert('hello!')"
Example:
<HTML><BODY>
<P> Click on the button below. </P>
<FORM NAME="frm1">
<INPUT TYPE="Button" NAME="cmdClickMe" VALUE="ClickMe" onClick="ClickMe()">
</FORM> <SCRIPT>
function ClickMe()
{ alert("A simple example of Button action. onClick Events")
}
</SCRIPT> </BODY></HTML>
28 K. L. Narayana
JAVAScript
Example:
<HTML><form name="go">
Light Blue<input type="checkbox" name="C1" onclick="document.bgColor='lightblue'">
Yellow<input type="checkbox" name="C2" onclick="document.bgColor='yellow'">
Light Green<input type="checkbox" name="C3" onclick="document.bgColor='lightgreen'">
</form> </html>
<body onload="inform()"> //Execution of code will begin after the page has loaded.
<frameset onload="inform()"> //Execution of code will begin after current frame has loaded.
<img src="whatever.gif" onload="inform()"> //Execution begin after the image has loaded.
Example
<html> <head><title>Body onload example</title></head>
<body onload="alert(‘Hello students welcome to Java Script Class by KLN’)">
<font color=red face=impact size=6> Welcome to my Java Script pages </font>
</body> </html>
onUnload
onunload executes JavaScript immediately after someone leaves the page. A common use (though not that
great) is to thank someone as that person leaves your page for coming and visiting.
Example
<body onunload="alert('Thank you. Please come back to this site and visit again, ok?')">
Example33.html:
<html> <head>
<font color=red size=5> Click the below link to visit My Web Designing Examples. </font>
<br><br><br><script>
num=0
function handler()
{ return confirm("Are you sure you want to visit Web Designing Examples. . . ")
}
</script> </head> <body>
<a href="../webtutorials.html" onClick='return handler()'> Web Designing Examples </a>
</body></html>
Output:
K. L. Narayana 29
JAVAScript
19) FORM OBJECT
Each form in a document creates a Form object. A document can contain more than one form, Form objects
are stored in an array called forms as the first forms[0], the second forms[1], and so on. In addition to
referring to each form by name, you can refer to the first form in a document as document.forms[0]
Likewise, the elements in a form, such as text fields, radio buttons, and so on, are stored in an elements
array. So you could refer to the first element of the first form as document.forms[0].elements[0]
CREATING FORM:
Forms are created by using the <form> tag. You can set attributes for Form.
Form Attributes/Properties:
action, name, target, method, elements[]
Form Elements:
Text object, Button object, Checkbox object, Radio object, Select object, Textarea object, Buttoon object
Accessing a Form:
document.forms[0] or document.formName
TEXT OBJECTS
Each of the four text–related HTML form elements– text, textarea, password, and hidden.
BUTTON OBJECT
There are three types of buttons, button submit and reset.
CHECKBOX OBJECT
The key property of a checkbox object is whether or not the box is checked. The checked property is a
Boolean value; true if the box is checked, false if not.
Example34.html
<html><head><title>check box example</title>
<script language="JScript" >
function inspect()
{ if(document.forms[0].checkThis.checked)
alert("You Can Collect Soft Copy of Web Designing from your instructors. . .");
else
alert("Fine. You take examples in Floppy form your respective computers!");
}
</script></head><body bgcolor=slate text=red>
<div align=center><h2>Are you want Soft copy of Web Designing Examples. . .</h2>
<br><br>
<form> <input type=checkbox name=checkThis >Soft Copy Wanted<br><br><br><br>
<input type=button value="Inspect Box" onClick=inspect()>
</div> </form></body></html>
30 K. L. Narayana
JAVAScript
Output:
K. L. Narayana 31
JAVAScript
Two important properties of an option item are text and value, accessed as follow:
Document.form[0].selectName.options[n].text
Document.form[0].selectName.options[n].value
The text property is the string that appears on screen in the selected object, the text is defined outside of the
<option> tag. But inside the <option> tag you can set a VALUE attribute, which like the radio buttons
shown earlier. This value is the index number of the item that is currently selected.
Example36.html
<html>
<head><script language=JScript>
function goThere()
{ var list = document.formselect.branch
var location = list.options[list.selectedIndex].text
alert("You have choosen a " + location +" Branch ")
}
</script></head>
<body> <form name=formselect><h3>
Choose Your Branch ::
<select name=branch onChange=goThere()>
<option selected value=CSE>Computer Science Engineering
<option value=IT>Information Technology
<option value=ECE>Electronics & Communication Engineering
<option value=ECE>Electrical & Electronics Engineering
<option value=ECE>Civil Engineering
<option value=ECE>Mechanical Engineering
</select> </form></body></html>
Output:
32 K. L. Narayana
JAVAScript
if (reg.test(emailField.value) == false)
{
alert('Invalid Email Address'); return false;
}
else
{
alert('Thank you for entereing Valid Email...'); return true;
}
}
catch(Exception) { alert(Exception.message) }
}
</script> </body> </html>
Output:
Example39.html: Enter all the Text Fields without leaving empty which are compulsory
<HTML>
<HEAD><TITLE>Elements Array</TITLE>
<SCRIPT LANGUAGE="JavaScript">
function verifyIt()
{ var form = document.forms[0]
for (i = 0; i < form.elements.length; i++)
{ if (form.elements[i].type == "text" && form.elements[i].value == "")
{ alert("Please fill out all fields.")
form.elements[i].focus()
return false;
}
}
alert("Thank You for Filling the Form");
}
</SCRIPT>
</HEAD>
34 K. L. Narayana
JAVAScript
<BODY bgcolor=cyan text=navy> <h2> Enter Your Details</h2>
<FORM><table cellspcing=5><tr><td>Enter your first name <td>
<INPUT TYPE="text" NAME="firstName" onKeyReleased=verifyIt()>
<tr><td>Enter your last name <td> <INPUT TYPE="text" NAME="lastName">
<tr><td>Enter Your Gender<td>
<INPUT TYPE="radio" NAME="gender" checked>Male
<INPUT TYPE="radio" NAME="gender">Female
<tr><td>Enter your Email–ID<td><INPUT TYPE="text" NAME="email">
<tr><td>Enter your Place of Birth <td><INPUT TYPE="text" NAME="city"></table>
</FORM><CENTER><FORM>
<INPUT TYPE="button" NAME="act" VALUE="Verify" onClick="verifyIt()">
</FORM></CENTER> </BODY></HTML>
Output:
K. L. Narayana 35
JAVAScript
HOW TO Enable JAVAScript in Google Chrome.....
1) first seelct the settings of the chrome.
3) click on the advanced you will get Privacy and Security and click on Content Settings
36 K. L. Narayana
JAVAScript
4) click on javascript
5) you will get one new window you can set Allowed for javascript.
K. L. Narayana 37
JAVAScript
HOW Enable DEBUGGER of JAVAScript in Google Chrome
Generally we required the debugger when the output is not coming.
1) Press the F12 function key in the Chrome browser to launch the JavaScript debugger.
you will get the ERROR at line number 3 print is not a function
3) Open the source code of the javascript file and modify the code.
<html> <body> <script>
var x=10
document.print("Value of x = " + x);
</script> </body></html>
It provides code re usability because single JavaScript file can be used in several html pages.
An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript files
into a single file. It increases the speed of the webpage.
Let’s create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.
message.js
function msg()
{
alert("Hello welcome to KLN JAVAScript Classes...");
}
Let’s include the JavaScript file into html page. It calls the JavaScript function on button click.
index.html
<html>
<head>
<script type="text/javascript" src="message.js"> </script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form> </body> </html>
Output:
K. L. Narayana 39