UNIT-2
Introduction to JavaScript
JavaScript is a cross platform, object-based scripting language invented
specifically for use in web browsers to make websites more dynamic and
attractive.
JavaScript originated with Netscape and it is invented by Brendan Eich.
Adding JavaScript to our code allow us to change how the document
looks completely, from changing text, to changing colours, to changing
the options available in a drop down list.
Script is nothing but a small program which is generally very easy to
learn and use.
JavaScript can run on both client-side and server-side, but it is popular
among client side scripting languages.
JavaScript is a programming language that can be written into HTML
documents to increase interactivity with the user.
JavaScript is easy to implement, as a compiler is not needed for
execution.
JavaScript provides the facility of event driven programming.
JavaScript is architecture neutral language and is independent of the
hardware on which it works.
It is language that is understood by any JavaScript enabled browsers.
JavaScript is a case-sensitive language.
JavaScript has the ability to function both as an object-oriented language
as well as procedural language.
Using JavaScript we can create, attach methods and properties.
Why JavaScript?
We have two kinds of methods to valid the entire data form.
One is to validate it on server side.
Client-side scripting should be used instead of server side validations like
email address validations, some textboxes are empty or not.
Client-side validation makes the browsing faster.
JavaScript can respond to several events that occur on web-pages and
which help in designing dynamic and interactive websites.
What can JavaScript do?
1) Display information based on the time of the day
JavaScript can check the computer’s clock and pull the
appropriate data based on the clock information.
2) Detect the visitor’s browser
JavaScript can be used to detect the visitor’s browser and
load another page specifically designed for that browser.
3) Control Browsers
JavaScript can open pages in customized windows, where
we specify if the browser’s buttons, menu line, status line or
whatever should be present.
4) Validate forms data
JavaScript can be used to validate form data at the client-side
saving both the server resources and time.
5) Create cookies
JavaScript can store information on the visitor’s computer
and retrieve it automatically next time the user visits the
page.
6) Add interactivity to the website
JavaScript can be set to execute when something happens,
like when a page has finished loading or when a user clicks a
button.
7) Change page contents dynamically
JavaScript can randomly display content without the
involvement of server programs.
It can read and change the content of an HTML element or
move them around pages.
Features of JavaScript
a) A great programming tool for HTML
JavaScript is powerful scripting language that helps HTML
designers to effectively and interactively design websites
and webpages in a very simple and efficient way.
b) Handles Dynamic Behaviour
JavaScript is such a powerful scripting language which has
features to achieve dynamic behaviour in webpages.
c) Browser Detection
JavaScript has the ability to detect client-browser which
helps in achieving independent platforms.
JavaScript can detect the type of browser the visitor is using
and programmatically switch the page to show customized
pages designed for different browsers.
d) Saves Time
JavaScript validates the data submitted at the client level.
This helps in saving the processing time of the server
because JavaScript creates the validation on the client side.
e) DOM
Client-side JavaScript is embedded inside HTML. This
embedded JavaScript is used along with DOM( Document
Object Model) for control over the browser by means of
objects.
f) Popular Scripting Languages
JavaScript has simple rules and procedures that make it
easier to use and learn for programmers.
g) Interpreted Language
It can be used or executed with ease without pre-
compilation.
Advantages and Disadvantages
Advantages
i. Less server interaction
We can validate user input before sending the page to the
server which saves server traffic.
ii. Immediate feedback to the visitors
The users don’t have to wait for a page to reload to see if
they have forgotten to enter something.
iii. Increased interactivity
We can create interfaces that react when the users hovers
over them with a mouse or activates them via the keyboard.
iv. Event-driven programming
JavaScript recognizes when a form ‘button’ is pressed.
This event can have the suitable JavaScript code attached,
which will execute when the ‘button pressed’ event occurs.
v. GUI features
Many ‘GUI features’ such as alerts, prompts, confirm boxes and
other GUI elements are handled by client-side JavaScript.
Disadvantages
a) Client-side JavaScript does not allow the reading or writing of files. This
has been kept for security reasons.
b) JavaScript cannot be used for networking applications because there is no
support available.
c) JavaScript doesn’t have any multithreading or multi-process capabilities.
Java Vs JavaScript
JavaScript Java
a) JavaScript is high level a) Java is high level object
object-based scripting oriented language.
language.
b) JavaScript does not permit b) Java allows creating
programmers to create standalone applications.
standalone applications.
c) JavaScript is simpler language c) Java is complex language
and easy to learn. when compared to JavaScript.
d) JavaScript does not have any d) Java has a compiler.
compiler.
e) JavaScript is interpreted e) Java is compiled and
language and it is interpreted interpreted language.
by the browser.
f) JavaScript is text-based. We f) Once the Java is compiled,
write it to an HTML we cannot modify the byte
document and it runs through code. We can go back to the
a browser. We can alter it, original text and alter it, but
after it runs and run it again then we need to compile
and again. again.
g) Prototype based object model. g) Class based object model.
h) Light weight language. h) Strong type language.
How JavaScript works?
1. We type the URL in the browser. The browser sends the http
request to server to get the webpage we have requested.
2. Server checks the request and returns the HTML page to the
browser.
3. The Browser gets the HTML page and displays the content. The
entire HTML page is now with browser. The JavaScript code is
also embedded in the HTML.
4. Assume that user gets Feedback form. The user will type the values
in the text box and submits the form. We need to validate the form.
If JavaScript is available in HTML page to validate the form, then
JavaScript code will be executed before sending the form details to
server.
JavaScript syntax
JavaScript syntax refers to a set of rules that determine how the
language will be written and interpreted.
The JavaScript syntax is loosely based on the Java syntax.
A JavaScript consists of JavaScript statements that are placed
within the <script>………………..</script> HTML tags in a
webpage.
We can place the <script> tag containing the JavaScript anywhere
within the webpage but it is preferred way to keep it within the
<head> tags.
The <script> tag alerts the browser program to begin interpreting
all the text between these tags as a script.
Syntax:
<script type=”text\javascript”>
JavaScript code
</script>
Type attribute: This attribute indicates the scripting language in
use and its value should be set to “text/javascript”.
Where to put script?
We can place JavaScript in any of the following locations:
Between the HTML document’s head tags.
Within the HTML document’s body(i.e., Between the body
tags)
In an external file (and link to it from the HTML document).
In the Head section
As the head loads before the body, it is guaranteed that it is
available when needed.
Hence, it reduces the scope of errors.
<html>
<head>
<script type=”text\javascript”>
The script tag has been placed inside the head section.
</script>
</head>
</html>
If a programmer wants to execute JavaScript when called, or when
an event is triggered, then JavaScript is placed in the HEAD
section.
In the Body Section
Place the script tag in the body section, if we want to generate
certain content on the page when it loads.
<html>
<body>
<script type=”text\javascript”>
document.write(“Here script tag has been placed inside the
body section.”);
</script>
</body>
</html>
When a programmer wants to execute JavaScript when the page
loads then JavaScript should be placed in the BODY section.
In an External File
When we want to use the same script on different pages, we can
use this external file.
The advantage of using external file is that we don’t need to
rewrite.
External JavaScript file is saved with a “.js”extension.
<html>
<head>
<script type=”text\javascript”
src=”common.js”>
</script>
</head>
<body>
</body>
</html>
Here, the JavaScript code is written in a file called “common.js”.
The file is linked to an HTML page using “src” attribute of the
script.
JavaScript Comments
Single-line comments: //
Multiline comments: /* and */
//This is a single line comment.
/*
*This is a multi
*line comment
*/
/*
This is also a valid
Multiline comment
*/
JavaScript Variables
Declaring Variables
A variable is a named element used to store and retrieve information.
With variables, we can store information in one part of the program and
access information from that variable in another part of the program.
The process of creating a variable is also known as declaring a variable.
Declaring variable using var command
To declare a variable in JavaScript, use the var command.
var age;
var state, city, zip, country;
Note:
1. A variable name cannot be one of the reserved words in JavaScript.
2. The first letter of a variable name must be a letter or an underscore(_).
3. A variable name cannot contain any space characters. If a variable
consists of more than one word, separate each word with an underscore.
Declaring variable without var command
We can declare variables simplicitly by using the assignment operator to
assign a value to new variable.
Ex1: age=100;
Ex2: <script type=”text\javascript”>
sum=x=y=0;
</script>
Ex3: <script type=”text\javascript”>
var sum, x, y;
sum=x=y=0;
</script>
Assigning values to variables
Ex1: var age;
age =55;
Ex2: age=55;
Ex3: <script type=”text\javascript”>
var name, age;
name =”Snigda”;
age =55;
document.write(name+”is”+age);
</script>
Variable scope in JavaScript
The availability or accessibility of a variable within an executing program
is referred to as variable scope.
If a variable is available only in certain part of the program, it is said to
have local scope.
If a variable is accessible throughout the program, it is said to have global
scope.
Local Scope
Variables declared in a function have a local scope.
Once the function is returned, the variables inside the function are
destroyed.
Ex:
<script type=”text\javascript”>
function testVariableScope()
{
var scope=”local”;
document.write(scope);
}
testVariableScope();
document.write(scope);
</script>
Global Scope
Variables declared outside of a function have global scope.
Ex:
<script type=”text\javascript”>
var scopeGlobal=”global”;
function testScope()
{
var scopelocal=”local”;
document.write(ScopeLocal);
document.write(ScopeGlobal);
}
testScope();
document.write(scopeGlobal);
</script>
Functions
A function is a series of commands that either calculates a value or
performs an action.
A function consists of function name, parameters, the values
passed to the function, and the set of commands that run when the
function is called.
The general syntax of a JavaScript function is:
function functionName(parameters)
{
JavaScript Commands
}
Where
functionName= name of the function
parameters= values sent to the functions
JavaScript commands= Commands that run when the
function is called or used.
Performing an action with a function
Let us start with a simple JavaScript function that will print a
message to the screen.
Ex:
function DisplayMessage( )
{
document.write(“JavaScript is very easy”);
}
To call the DisplayMessage function, we write
DisplayMessage( );
Ex:
<script type= “text/javascript”>
function DisplayMessage( )
{
document.write(“JavaScript is very esay”);
}
document.write(“Calling the function…<br\>”);
DisplayMessage( );
document.write(“<br\>Done!”);
Output:
Calling the function…
JavaScript is very easy.
Done!
Passing Parameters to functions
Ex:
<script type= “text\javascript”>
function DisplayMessage(message)
document.write(message+”<br/>”);
DisplayMessage(“Hello”);
DisplayMessage(“Mr.John”);
</script>
Returning a value from a function
Ex:
function isEven(num)
if(num%2==0)
return num;
The sort( ) method using call back functions
We can also define our own sorting function using call back
functions.
This call back function must have two input arguments and always
returns -1, 0 or 1.
If call back func (a,b) is less than 0, place a before b.
If call back func(a,b) returns 0, leave a and b unchanged in respect
to eachother.
If call back func(a,b) is greater than 0, place a after b.
Ex: var MyArray= new Array( );
myArray= [20, 10, 40, 50, 30];
function callbackFunc(a,b)
{
return a-b;
}
myArray.sort(callbackFunc);
Validation API
Constraint Validation DOM Properties
Property Description
a. Validity Contains Boolean properties related to the
validity of an input element.
b. ValidationMessage Contains the message a browser will display
when the validity is false.
c. willValidate Indicates if an input element will be validated.
Validity Properties
The validity property of an input element contains a number of properties
related to the validity of data:
Property Description
a) customError Set to true, if a custom validity message
is set.
b) patternMismatch Set to true, if an elements value does not
match its pattern attribute.
c) rangeOverflow Set to true, if an elements value is greater
than its max attribute.
d) rangeUnderflow Set to true, if an elements value is less
than its min attribute.
e) stepMismatch Set to true, if an elements value is invalid
per its step attribute.
f) tooLong Set to true, if an elements value exceeds
its maxLength attribute.
g) typeMismatch Set to true, if an elements value is invalid
per its type attribute.
h) valueMissing Set to true, if an element( with a required
attribute) has no value.
i) Valid Set to true, if an elements value is valid.
Examples
If the number in an input field is greater than 100, display a message.
The rangeOverflow Property
<input id=”id1” type=”number” max=”100”>
<button onclick=”myFunction( )”>OK</button>
<p id=”demo”></p>
<script>
function myFunction( )
var txt= “”;
if(document.getElementById(“id1”).Validity.rangeOverflow)
txt= “Value too Large”;
document.getElementById(“demo”).innerHTML= txt;
}
</script>
Example: If the number in an input field is less than 100, display a message:
The rangeUnderflow Property
<input id=”id1” type=”number” min=”100”>
<button onclick=”myFunction( )”>OK</button>
<p id=”demo”></p>
<script>
function myFunction( )
var txt= “”;
if(document.getElementById(“id1”).Validity.rangeUnderflow)
txt= “Value too Small”;
document.getElementById(“demo”).innerHTML= txt;
}
</script>
Document Object Model (DOM)
The document object model (DOM) is an application programming
interface (API) for HTML documents. The DOM represents a document
as a hierarchial tree of nodes, allowing developers to add, remove and
modify individual parts of webpage.
The DOM is a way of representing the document independent of browser
type. It allows a developer to access the document via a common set of
objects, properties, methods and events and to alter the contents of the
webpage dynamically using scripts.
The DOM explains what properties of a document a script can retrieve
and which ones it can alter, it also defines some methods that can be
called to perform an action of the document.
Using DOM we can change anything on the page; the graphics, tables,
forms, and text by altering relevant DOM property.
Levels of DOM
1) DOM 0
All browsers have a DOM which gives you access to various parts
of the document.
The level 0 DOM is the oldest of them.
It was implemented in NetScape2 and 3 and still works in all
JavaScript browsers.
It gives easy access to forms and their elements, images and links.
2) DOM 1
The initial DOM standard known as “DOM level 1”, was
recommended by W3C in 1998.
DOM level 1 provided a complete model for an entire HTML or
XML document, which included means to change any portion of
the document.
3) DOM 2
Level 2 is complete and many of the properties, methods and
events have been implemented by today’s browsers.
It has sections that add specifications for events and stylesheets.
4) DOM 3
Level 3 achieved recommendation status in 2004.
It is intended to resolve lot of complications that still exist in the
event model in level-2 of the standard.
This adds support for XML features, such as content models.
Only a few browsers support some features of level 3.
Tree Representation of Dom
document
<html>
<head> <body>
<title>
<h1> <p> <table>
<tr>
<tr>
<td
> <td> <td>
DOM Objects
1) Window Location
The window.location object can be used to get the current page
address (URL) and to redirect the browser to a new page.
The window.location.href property returns the URL of the current
page.
Ex:
document.getElementById(“demo”).innerHTML=
“page Location is”+window.location.href;
Window Location Hostname
The window,location.hostname property returns the name of the
internet host (of the current page).
Ex:
Document.getElementById(“demo”).innerHTML=”pagehostna
me is”+window.location.hostname;
2) Window History
The window.history object contains the browser history,
To protect the privacy of the users, there are limitations to how
JavaScript can access this object.
history.back( )- same as clicking back in the browser.
history.forward( )- same as clicking forward in the browser.
Window History Back
The history.back( ) method loads the previous URL in the
history list.
Ex: Create a back button on a page
<html>
<head>
<script>
function goBack( )
{
window.history.back( );
}
</script>
</head>
<body>
<input type=”button” value=”Back”
onclick=”goBack( )”>
</body>
</html>
Window History Forward
The history forward( ) method loads the next URL in the history
list.
Ex: Create a forward button on a page
<html>
<head>
<script>
function goForward( )
{
window.history.forward( );
}
</script>
</head>
<body>
<input type=”button” value=“Forward”
onclick=”goForward( )”>
</body>
</html>
3) Window Navigator
The window.navigator object contains information about the
visitor’s browser.
Ex:
navigator.appName
navigator.appCodeName
navigator.platform
Browser Application Name
The appName property returns the application name of the
browser.
Ex:
<p id=”demo” ></p>
<script>
document.getElementById(“demo”).innerHTML=
“navigator.appName is”+navigator.appName;
</script>
Browser Application Code Name
The appCodeName property returns the application code name
of the browser.
Ex:
<p id=”demo”></p>
<script>
document.getElementById(“demo”).innerHTML=
“navigator.appCodeName is”+navigator.appCodeName;
</script>
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 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 used to trap user-initiated events such as
button clicks, link navigation, and other actions that the user
initiates explicitly or implicitly.
Server side scripting:
Web servers are used to execute server side scripting.
They are basically used to create dynamic pages.
It can also access the file system residing at web server.
Server-side environment that runs on a scripting language is a
web-server.
Scripts can be written in any of a number of server-side scripting
languages available.
It is used to retrieve and generate content for dynamic pages.
It is used to download plugins.
In this load times are generally faster than client-side scripting.
When you need to store and retrieve information a database will
be used to contain data.
It can use huge resources of server.
It reduces client-side computation overhead.
Server sends pages to request of user/client.
JavaScript - Objects
JavaScript is an Object Oriented Programming (OOP) language.
A programming language can be called object-oriented if it provides
four basic capabilities to developers −
1. Encapsulation − the capability to store related information, whether data
or methods, together in an object.
2. Aggregation/Abstraction − the capability to store one object inside
another object.
3. Inheritance − the capability of a class to rely upon another class (or
number of classes) for some of its properties and methods.
4. Polymorphism − the capability to write one function or method that
works in a variety of different ways.
Objects are composed of attributes.
If an attribute contains a function, it is considered to be a method of the
object; otherwise the attribute is considered a property.
Object Properties
Object properties are usually variables that are used internally in the
object's methods, but can also be globally visible variables that are used
throughout the page.
The syntax for adding a property to an object is −
objectName.objectProperty = propertyValue;
Ex: var str = document.title;
Object Methods
Methods are the functions that let the object do something or let
something be done to it.
There is a small difference between a function and a method.
Function is a standalone unit of statements and a method is attached to
an object and can be referenced by this keyword.
Methods are useful for everything from displaying the contents of the
object to the screen to performing complex mathematical operations on a
group of local properties and parameters.
document.write("This is test");
User-Defined Objects
All user-defined objects and built-in objects are descendants of an object
called Object.
The new Operator
The new operator is used to create an instance of an object.
To create an object, the new operator is followed by the constructor
method.
These constructors are built-in JavaScript functions.
Core Javascript (Properties and methods of each)
Arrays
An array is an ordered collection of values that is grouped together by a
single variable name.
Each element of the array is accessed with an index value enclosed in
square brackets.
An index is also called a subscript.
There are two types of index values: a nonnegative integers and a string.
Arrays indexed by numbers are called numeric arrays.
Arrays indexed by strings are called associative arrays.
Creating an Array object using new
The new keyword is used to dynamically create the array object.
Array object’s constructor function, Array( ), to create a new Array
object.
The size of the array can be passed as an argument to the constructor.
Ex1: var array_name=new Array( );
Ex2: var months=new Array( );
months[0]= “January”;
months[1]= “February”;
months[2]= “March”;
The size or length of the array can also be passed as an argument to the
Array( ) constructor.
The new array has 100 undefined elements
var array_name=new Array(100);
Ex: var weekday =new Array(“ Sunday”, “Monday”, ”Tuesday”);
The values can be of any data type or combination of types.
Creating an Array literal
The array literal is a quick way to create and populate an array.
To use a literal notation, the array is given a name and assigned a list of
elements.
The elements are separated by commas and enclosed between a set of
square brackets.
Ex: var bestplaces=[“Agra”, “London”, “Bangalore”];
Characteristics or properties of Array objects
Ex: var bestplaces= new Array(5);
document.write(“length is :”+bestPlaces.length);
Ex: var bestPlaces= new Array( );
document.write(“length is:”+bestPlaces.length);
Ex: varbestPlaces= new Array(5);
bestPlaces[0]=”Agra”;
document.write(“length is:”+bestPlaces.length);
bestPlaces[19]=”Hyderbad”;
document.write(“length is:”+bestPlaces.length);
Array Methods
Array methods are used to manipulate arrays such as adding a new
element at the beginning or end of an array, removing an element
from the end of an array, reversing an array and so on.
JavaScript provides a set of methods for doing all of these.
a) concat( )-concatenates elements from one array to
another array.
b) join( )- Joins the elements of an array by a separator to
form a string.
c) pop( )-Removes and returns the last elements of an array.
d) push( )-Adds elements to the end of an array.
e) reverse( )- Reverses the order of elements in an array.
f) shift( )-Removes and returns the first element of an array.
g) slice( )-Creates a new array from elements of an existing
array.
h) sort( )-Sorts an array alphabetically or numerically.
i) splice( )-Removes and/or replaces elements of an array.
j) toLocaleString( )- Returns a string representation of the
array in local format.
k) toString( )- Returns a string representation of the array.
l) unshift( )- Adds elements to the beginning of an array.
1. The concat( ) Method
The concat( ) method concatenates the elements passed as
arguments onto an existing array, returning a new concatenated list.
The method does not change the existing array.
We must assign results to either an existing array or a new one.
Ex:
var bestPlaces = new Array(5);
bestPlaces[0] = “Agra”;
bestPlaces[1] = “London”;
var newPlaces = bestPlaces.concat(“Pune”,”Delhi”);
bestPlaces- 2
newPlaces- 4
2. The pop( ) Method
The pop( ) method deletes the last element of an array and returns
the value poped off.
Ex:
var bestPlaces= new Array(5);
bestPlaces[0]= “Agra”;
bestPlaces[1]= “London”;
bestPlaces[2]= “Bangalore”;
var deletedPlace= bestPlaces.pop( );
document.write(“Deleted Place is” +deletedPlace);
3. The push( ) Method
The push( ) method adds new elements onto the end of an array,
thereby increasing the length of the array.
Ex:
var bestPlaces= new Array( );
bestPlaces[0]= “Agra”;
bestPlaces.push= (”London”,”Bangalore”);
bestPlaces array contains three elements.
4. The shift( ) and unshift( ) Methods
The shift( ) method removes the first element of an array and
returns the value shifted off.
The unshift( ) method adds elements to the beginning of the array.
Ex:
var bestPlaces= new Array( );
bestPlaces[0]= “Agra”;
bestPlaces[1]= “London”;
var deletedPlace= “bestPlaces.shift( )”;
bestPlaces.unshift(“Agra”,”Bangalore”);
(OR)
bestPlaces.shift(“Agra”,”Bangalore”);
5. The slice( ) method
The slice( ) method copies elements of one array into a new array.
The slice( ) method takes two arguments.
The first is the starting element in a range of elements that will be
copied.
The second is the last element in the range, but this element is not
included in what is copied.
Ex:
var bestPlaces= new Array( );
bestPlaces[0]= “Agra”;
bestPlaces[1]= “Bangalore”;
bestPlaces[2]= “London”;
bestPlaces[3]= “Paris”;
bestPlaces[4]= “Newyork”;
var selectPlaces= bestPlaces.slice(2, 4);
The selectPlaces contains elements 2 through 3 of bestPlaces. It
contains “London” and “Paris”.
6. The join( ) Method
The join( ) method converts all of the elements of an array to
strings and concatenates them into a single string.
If no parameter is provided to join( ) method, then all the strings
are separated by comma.
Ex:
var bestPlaces= new Array(“Agra”,”Bangalore”,”London”);
var combinedArray= bestPlaces.join(“->”);
The value of the combined array is:
Agra->Bangalore->London
7. The reverse( ) Method
The reverse( ) method reverses the order of the elements in an
array.
Ex:
var bestPlaces= new Array(“Agra”, ”Bangalore”, ”London”);
bestPlaces.reverse( );
8. The sort( ) Method
The sort( ) method sorts the elements in alphabetical order.
Ex:
var bestPlaces= new Array(“Paris” ,”Bangalore”,” Agra”);
bestPlaces.sort( );
Boolean
The Boolean object represents two values, either "true" or "false".
If value parameter is omitted or is 0, -0, null,
false, NaN, undefined, or the empty string (""), the object has an
initial value of false.
Syntax
var val = new Boolean(value);
Boolean Properties
Sl NO Property Description
1. Constructor Returns a reference to the
Boolean function that
created the object.
2. Prototype The prototype property
allows you to add
properties and methods to
an object.
Boolean Methods
Sl NO Method Description
1. toSource( ) Returns a string containing
the source of the Boolean
object; you can use this
string to create an
equivalent object.
2. toString( ) Returns a string of either
"true" or "false" depending
upon the value of the
object.
3. valueOf( ) Returns the primitive value
of the Boolean object.
Date
The Date object is a datatype built into the JavaScript language.
Date objects are created with the new Date( ) as shown below.
Once a Date object is created, a number of methods allow you to
operate on it.
Most methods simply allow you to get and set the year, month,
day, hour, minute, second, and millisecond fields of the object,
using either local time or UTC (universal, or GMT) time.
Syntax
new Date( )
new Date(milliseconds)
new Date(datestring)
new Date(year,month,date[,hour,minute,second,millisecond ])
.
Here is a description of the parameters −
No Argument − With no arguments, the Date() constructor creates a
Date object set to the current date and time.
milliseconds − When one numeric argument is passed, it is taken as the
internal numeric representation of the date in milliseconds, as returned
by the getTime() method.
datestring − When one string argument is passed, it is a string
representation of a date, in the format accepted by
the Date.parse() method.
7 agruments − To use the last form of the constructor shown above.
Here is a description of each argument −
o year − Integer value representing the year.
For compatibility , you should always specify the year in
full; use 1998, rather than 98.
o month − Integer value representing the month, beginning with 0
for January to 11 for December.
o date − Integer value representing the day of the month.
o hour − Integer value representing the hour of the day (24-hour
scale).
o minute − Integer value representing the minute segment of a time
reading.
o second − Integer value representing the second segment of a time
reading.
o millisecond − Integer value representing the millisecond segment
of a time reading
Date Properties
Sl NO Property Description
1. Constructor Specifies the function that
creates an object's
prototype.
2. Prototype The prototype property
allows you to add
properties and methods to
an object
Date Methods
Sl NO Method Description
1. Date( ) Returns today's date and
time
2. getDate( ) Returns the day of the
month for the specified
date according to local
time.
3. getDay( ) Returns the day of the
week for the specified date
according to local time.
4. getFullYear( ) Returns the year of the
specified date according to
local time.
5. getHours( ) Returns the hour in the
specified date according to
local time.
6. getMilliseconds( ) Returns the milliseconds
in the specified date
according to local time.
7. getMinutes( ) Returns the minutes in the
specified date according to
local time.
8. getMonth( ) Returns the month in the
specified date according to
local time.
9. getTime( ) Returns the numeric value
of the specified date as
the number of milliseconds
since January 1, 1970,
00:00:00 UTC.
10. getTimezoneOffset( ) Returns the time-zone
offset in minutes for the
current locale.
11. getUTCDate( ) Returns the day (date) of
the month in the specified
date according to
universal time.
12. getUTCDay( ) Returns the day of the
week in the specified date
according to universal
time.
13. getUTCFullYear( ) Returns the year in the
specified date according to
universal time.
14. getUTCHours( ) Returns the hours in the
specified date according to
universal time.
15. getUTCMilliseconds( ) Returns the milliseconds
in the specified date
according to universal
time.
16. getUTCMinutes( ) Returns the minutes in the
specified date according to
universal time.
17. getUTCMonth( ) Returns the month in the
specified date according to
universal time.
18. getUTCSeconds( ) Returns the seconds in the
specified date according to
universal time.
19. setDate( ) Sets the day of the month
for a specified date
according to local time.
20 setFullYear() Sets the full year for a
specified date according to
local time.
Function object
JavaScript function objects are used to define a piece of JavaScript code.
This code can be called within a JavaScript code as and when required.
Can be created by function constructor.
Code defined by a function can be called by function().
Javascript Function Objects Property
Sl NO Property Description
1. arguments An array corresponding to
the arguments passed to a
function.
2. arguments.callee Refers the currently
executing function.
3. arguments.length Refers the number of
arguments defined for a
function.
4. constructor Specifies the function that
creates an object.
5. length The number of arguments
defined by the function.
6. prototype Allows adding properties to a
Function object.
Javascript Function Objects Methods
Sl NO Method Description
1. call Permit to call a method of
another object in the context
of a different object (the
calling object).
2. toSource- Returns the source code of
the function.
3. toString Returns a string representing
the source code of the
function.
4. valueOf Returns a string representing
the source code of the
function.
Math Object
The math object provides you properties and methods for mathematical constants
and functions. Unlike other global objects, Math is not a constructor. All the
properties and methods of Math are static and can be called by using Math as an
object without creating it.
Thus, you refer to the constant pi as Math.PI and you call the sine function
as Math.sin(x), where x is the method's argument.
Syntax
The syntax to call the properties and methods of Math are as follows
var pi_val = Math.PI;
var sine_val = Math.sin(30);
Math Properties
Sl NO Property Description
1. E/ Euler's constant and the
base of natural logarithms,
approximately 2.718.
2. LN2 Natural logarithm of 2,
approximately 0.693.
3. LN10 Natural logarithm of 10,
approximately 2.302.
4. LOG2E Base 2 logarithm of E,
approximately 1.442.
5. LOG10E Base 10 logarithm of E,
approximately 0.434.
6. PI Ratio of the circumference
of a circle to its diameter,
approximately 3.14159.
7. SQRT 1_2 Square root of ½;
equivalently, 1 over the
square root of 2,
approximately 0.707.
8. SQRT 2 Square root of 2,
approximately 1.414.
Math Methods
Sl NO Method Description
1. abs( ) Returns the absolute value
of a number.
2. acos( ) Returns the arccosine (in
radians) of a number.
3. asin( ) Returns the arcsine (in
radians) of a number.
4. atan( ) Returns the arctangent (in
radians) of a number.
5. atan2( ) Returns the arctangent of
the quotient of its
arguments.
Number Object
The Number object represents numerical date, either integers or floating-point
numbers. In general, you do not need to worry about Number objects because the
browser automatically converts number literals to instances of the number class.
Syntax
The syntax for creating a number object is as follows −
var val = new Number(number);
In the place of number, if you provide any non-number argument, then the argument
cannot be converted into a number, it returns NaN (Not-a-Number).
Number Properties
Here is a list of each property and their description.
Sl NO Property Description
1. MAX_VALUE The largest possible value a
number in JavaScript can
have
1.7976931348623157E+308
2. MIN_VALUE The smallest possible value
a number in JavaScript can
have 5E-324
3. NaN Equal to a value that is not a
number
4. NEGATIVE_INFINITY A value that is less than
MIN_VALUE.
5. POSITIVE_INFINITY A value that is greater than
MAX_VALUE
6. prototype A static property of the
Number object. Used to
assign new properties and
methods to the Number
object in the current
document
7. Constructor Returns the function that
created this object's
instance. By default this is
the Number object.
Number Methods
The Number object contains only the default methods that are a part of every
object's definition.
Sl NO Method Description
1. toExponential( ) Forces a number to
display in exponential
notation, even if the
number is in the range in
which JavaScript normally
uses standard notation.
2. toFixed( ) Formats a number with a
specific number of digits to
the right of the decimal.
3. toLocaleString( ) Returns a string value
version of the current
number in a format that
may vary according to a
browser's local settings.
4. toPrecision( ) Defines how many total
digits (including digits to
the left and right of the
decimal) to display of a
number.
5. toString( ) Returns the string
representation of the
number's value.
6. Valueof( ) Returns the number's
value.
Javascript object Object - Properties and
Methods
Parent of all JavaScript objects. it is a primitive javascript object type.
Can be created by Object constructor, for example, new object().
Javascript Objects Property
Sl NO Property Description
1. constructor Specifies the function that
creates an object's
prototype.
2. prototype Use to add new properties
and methods to an object.
Javascript Objects Methods
Sl NO Method Description
1. tosource Use to get a string
representation (source code)
of the object.
2. tostring Rrepresent the source code
of the specified object.
3. valueof Returns the primitive value of
the specified object.
4. watch Use to watch a particular
property of an object.
5. unwatch Use to remove a watch point
for a particular property set
by the watch() method.
JavaScript Operators
JavaScript operators are symbols that are used to perform operations on
operands.
var sum=10+20;
Here, + is the arithmetic operator and = is the assignment operator.
There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
JavaScript Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the
operands.
JavaScript Comparison Operators
The JavaScript comparison operator compares the two operands.
JavaScript Bitwise Operators
The bitwise operators perform bitwise operations on operands.
JavaScript Logical Operators
The following operators are known as JavaScript logical
operators.
JavaScript Assignment Operators
The following operators are known as JavaScript assignment operators.
JavaScript Special Operators
The following operators are known as JavaScript special operators.
String Object
String Properties and Methods
The strings in JavaScript are objects and JavaScript automatically
converts between string primitives and string objects.
Creating a string object:
var string1=new String(“ABCD”);
var string2=”ABCD”
String Properties:
Property Description
1. Constructor Returns a reference to the string
function that created the object.
2. Length Returns the length of the string.
3. Prototype The prototype property allows you to
add properties and method to an
object.
String Methods:
Method Description
1. charAt( ) Returns the character at the specified
index.
Ex: var b=’I am a JavaScript
Learner.’
document.write(b.charAt(7));
o/p: ‘a’
2. indexOf( ) Returns the index within the calling
string object of the first occurrence of
the specified value, or -1 if not found.
Ex: var a=’Hello World!’;
document.write(a.indexOf(‘l’));
o/p: 2.
If the same character occurs more
than once, this method gives the first
occurrence.
3. lastIndexOf( ) Returns the index within the calling
string object of the last occurrence of
the specified value, or -1 if not found.
Ex: var b =’I am a JavaScript
Learner’;
document.write(b.lastIndexOf(‘a’));
o/p: 20
because that’s the index of the last ‘a’
in the string.
4. search( ) Executes the search for a match
between a regular expression and a
specified string.
Ex: var str,result;
str=”JavaScript”;
result=str.search(“script”);
document.write(“Substring found at
position:”+result);
o/p:Substring found at position :4
5. substr( ) Returns the characters in a string
beginning at a specified location
through the specific number of
characters.
Ex: var a=”Hello World!”;
document.write(a.substr(4,8));
starts at the characters with index
4(‘o’) and then gives 8 characters, so
the output is 0 world!
6. substring() Returns the characters in a string
between two indexes into the string.
Ex: var a=’Hello World!’;
document.write(a.substring(4,8));
gives ‘o wo’, from the first ‘o’(index
4) to the second one (index 7).
7. toLowerCase( ) Returns the calling string value
converted to Lowercase.
Ex: var b=’Srikanth’;
document.write(b.toLowerCase( ));
o/p: ‘srikanth’
8. toUpperCase( ) Returns the calling string value
converted to uppercase.
Ex: var b=’Srikanth’;
document.write(b.toUpperCase( ));
o/p: ‘SRIKANTH’
Screen Output and Keyboard Input
JavScript can accept input and produce output on the basis of that input in
the same page.
Methods to show output
1) document.write( ) or document.writeln( )
2) window.alert( )
3) window.status( )
Methods for taking input from user
1. document.write(“some text”);
2. document.writeln(“some text”);
1. document.write( ) and document.writeln( )
Any JavaScript statement must end with a semicolon to mark the end of
the statement.
The document is an object and both write and writeln are methods.
The “write” method prints the text to the browser without attaching a
carriage return at the end of text.
The “writeln” method adds a carriage return to the end of text.
Ex1: <script type=”text/javascript”>
document.write(“ <pre> line1”);
document.write(“line2</pre>”);
</script>
o/p: line1line2
Ex2: <script type=”text/javascript”>
document.writeln(“ <pre> line1”);
document.writeln(“line2</pre>”);
</script>
o/p: line1
line2
2. window.alert( )
The alert( ) method is part of window object.
The alert( ) method shows the message in a small message
box.
The message box contains the string and an “ok” button on
it.
If the user presses the “ok” button the message box
disappears.
The message to be displayed has to be passed as parameter
to the alert( ) method.
The window’s alert( ) method is used to send a warning to
the user or alert him or her to do something.
Ex: <html>
<head>
<title>Alert Demo</title>
<script type=”text\javascript”>
window.alert(“your email id is incorrect.”)
</script>
</head>
</html>
3. window.status
The status is not a method and it is property of window
object.
The window.status property show the message in status bar.
The message to be displayed has to be assigned to the
window.status property.
Ex: <html>
<head>
<title> Status Demo</title>
<script type=”text\javascript”>
window.status=“It is my own webpage.”;
</script>
</head>
</html>
4. window.prompt( )
A prompt( ) method asks the user for some small amount of
information such as password, completion of a form input,
or personal information.
The prompt dialog box pops up with a simple textfield box.
After the user enters text into the prompt dialog box, its
value is returned.
This method takes two arguments: a string of text that is
displayed as a question to the user, prompting the user to do
something and another string of text that is the initial default
setting for the box.
If this argument is an empty string, nothing is displayed in
the box.
The prompt( ) method always returns a value.
If the user clicks the OK button all the text in the box is
returned.
Ex: <html>
<head>
<title> Prompt Demo</title>
<script type=”text\javascript”>
var name=window.prompt(“What is your name?”,””);
alert(“Welcome to My webpage!....”+name);
var age= window.prompt(“Tell me your age:”,”your
age”);
if(age==null)
{
window.alert(“Not sharing your age with me”);
}
else{
window.alert(age+”ïs young”);
}
</script>
</head>
</html>
5. window.confirm( )
The confirm box is used to answer a user’s answer to a
question.
The user must agree before order or delete a file where a yes
or no confirmation determines what will happen next.
Question mark will appear in the box with an OK button and
a Cancel button.
If the user clicks the OK button, true is returned, if he clicks
the cancel button, false is returned.
This method takes only one argument, the question that we
are going to ask the user.
Ex:
<html>
<head>
<title> Confirm Demo</title>
<script type=”text\javascript”>
var canFormat=window.confirm(“Do you want to format
the hard disk?”);
if(canFormat===true)
{
window.alert(“Your hard disk is formatted”);
}
else{
window.alert(Your hard disk is not formatted”);
}
</script>
</head>
</html>
Pattern Matching Using Regular Expression
A regular expression is an object that describes a pattern of characters.
The JavaScript RegExp class represents regular expressions, and both
strings.
RegExp define methods that use regular expressions to perform powerful
pattern-matching and search-and-replace functions on text.
Syntax
A regular expression could be defined with RegExp( ) constructor
as follows:
var pattern =new RegExp(pattern, attributes);
(OR)
var pattern= /pattern/attributes;
Here,
Pattern- A string that specifies the pattern of the regular
expression or another regular expression.
Attributes- An optional string containing any of the “g”, “i”
and “m” attributes that specify global, case-insensitive and
multiline matches.
Brackets
Brackets([ ]) have a special meaning when used in the context of regular
expression.
They are used to find a range of character.
Sr.No Expression and Description
1. […]
Any one character between the brackets.
2. [^…]
Any one character not between the brackets.
3. [0-9]
It matches any decimal digit from 0 through 9.
4. [a-z]
It matches any characters from lowercase a through lowercase
z.
5. [A-Z]
It matches any character from uppercase A through uppercase
Z.
6. [a-Z]
It matches any character from lowercase a through uppercase
Z.
Quantifiers
The frequency or position of bracketed character sequences and single
characters can be denoted by a special character.
Each special character has a specific connotation.
The +, *, ? and $ flags all follow a character sequence.
Sl. No Expression and Description
1. p+
It matches any string containing one or more p’s.
2. p*
It matches any string containing zero or more p’s.
3. p?
It matches any string containing atmost one p.
4. p{N}
It matches any string containing a sequence of Np’s.
5. p{2,3}
It matches any string containing a sequence of two or three
p’s.
6. p{2}
It matches any string containing a sequence of atleast two p’s.
7. p$
It matches any string with p at the end of it.
8. ^p
It matches any string with p at the beginning of it.
Literal Characters
Sr. No Character and Description
1. Alphanumeric
Itself
2. \0
The NULL character (\u0000)
3. \t
Tab (\u0009)
4. \n
Newline (\u000A)
5. \v
Vertical tab (\u000B)
6. \f
Form feed (\u000C)
7. \r
Carriage return (\u000D)
8. \xnn
The latin character specified by the hexadecimal number nn;
For example, \x0A is the same as \n.
9. \uxxxx
The Unicode character specified by the hexadecimal number
xxxx; For example,\u0009 is the same as \t.
10. \cx
The control character ^X; Ex: \cJ is equivalent to the newline
character \n.
Metacharacters
A metacharacter is an alphabetical character preceded by a backslash that
acts to give the combination a special meaning.
Sl. No Character and Description
1. .
A single character.
2. \s
A whitespace character (space, tab, newline)
3. \S
Non-whitespace character.
4. \d
A digit(0-9)
5. \D
A non-digit.
6. \w
A word character (a-z, A-Z, 0-9,-)
7. \W
A non-word character.
8. [\b]
A literal backspace( special case)
9. [aeiou]
Matches a single character in the given set.
10. [^aeiou]
Matches a single character outside the given set.
11. (foo|bar|baz)
Matches any of the alternatives specified.
Pattern Matching Methods of String
The string object provides four methods that work with regular
expressions. They are:
a) The match( ) method
The match( ) method is used to search for a pattern of characters
in a string.
It returns an array where each element of the array contains
each matched pattern that was found.
If no match is found, returns NULL.
With the g flag , match( ) searches globally through the string
for all matching substrings.
Ex:
<script type= “text\javascript”>
var matchArray= new Array( );
var string= “I love the smell of clover”;
var regex= /love/g;
matchArray= string.match(regex);
</script>
Each time the pattern \love\ is found in the string, it will be
assigned as a new element of the array called matchArray.
If the g modifier is removed, only the first occurrence of the
match will be returned, and only one element will be assigned to
the array matchArray.
b) The search( ) Method
The search( ) method is used to search for a pattern of
characters within a string.
Returns the index position of where the pattern was found in the
string.
The index starts at zero.
If the pattern is not found, -1 is returned.
Ex:
<script type=”text\javascript”>
var myString= “I love the smell of clover”;
var regex= /love/;
var index= myString.search(regex);
document.write(“Found the pattern”+regex+”at position”+index+”<br/>”);
</script>
c) The replace( ) Method
The replace( ) method is used to search for a string and replace
the string with another string.
The i modifier is used to turn off case sensitivity and g modifier
makes the replacement global.
All occurrences of the found pattern are replaced with the new
string.
Ex:
<script type= “text\javascript”>
var myString= “Tommy has a stomach ache.”;
var regex= /tom/i;
var newString= myString.replace(regex,”Mom”);
document.write(newstring+”<br/>”);
</script>
d) The split( ) Method
The string object’s split( ) method splits a single text into an
array of substrings.
When using the string object’s split( ) method, if the words in a
string are separated by commas, then the comma would be the
delimiter.
If the words are separated by colons, then the colons is the
delimiter.
Ex:
<script type= “text\javascript”>
var splitArray= new Array( );
var string= “apples:grapes:banana:plums:oranges”;
var regex=/:/;
splitArray= string.split(regex);
for(i=0;i<splitArray.length;i++)
{
document.write(splitArray[i]+”<br/>”);
}
</script>
Element Access in JavaScript
The elements of an HTML document have corresponding
objects that can be accessed in JavaScript code.
To get the elements in JavaScript code, we should first get the
address or reference to the corresponding elements.
There are several ways to get the address of HTML elements
1. Accessing form elements using forms and elements array
The general syntax for accessing a form elements:
document.forms[number].elements[number]
When the page is loaded, JavaScript makes an array forms in
which it puts all the forms that are on the page.
The first form is forms[0], the second is forms[1] etc.
Each form has another array in which JavaScript puts all the
elements in the form.
In the below HTML code we have two forms called “firstForm”
and “secondForm”.
Each form has 4 elements.
forms[0] represents “firstForm” and forms[1] represents
“secondForm”.
The first element in firstForm can be accessed using
document.form[0].elements[0].
Code to access form elements Html code
<body>
<form name=”firstForm”>
document.forms[0].elements[0] Input type=”text” name=”NameText”/>
document.forms[0].elements[1] Input type=”text” name=”AgeText”/>
document.forms[0].elements[2] Input type=”text” name=”PhoneText”/>
document.forms[0].elements[3] Input type=”submit” name=”myButton1”/>
</form>
<form name=”secondForm”>
document.forms[1].elements[0] Input type=”text” name=”CourseText”/>
document.forms[1].elements[1] Input type=”text” name=”SemText”/>
document.forms[1].elements[2] Input type=”text” name=”PercentageText”/>
document.forms[1].elements[3] Input type=”submit” name=”myButton2”/>
</form>
</body>
In the above code, we have used 3 text boxes and one submit button in
each form.
We can get the values entered in each textbox using value property in
JavaScript code
<script type=”text/javascript>
function function1( )
{
var Name= document.forms[0].elements[0].value;
var Age= document.forms[0].elements[1].value;
var Phone= document.forms[0].elements[2].value;
}
</script>
Disadvantage
Whenever new button or element is added to the form, the array
element will be re-ordered.
We should change the numbers in JavaScript code.
2. Accessing form elements using name attribute
In HTML, we have to give a name to each form and each element.
<form name=”firstForm”>
<input type=”text” name=”NameText/>
<input type=”text” name=”AgeText/>
<input type=”text” name=”PhoneText/>
<input type=”submit” name=”myButton1/>
</form>
Syntax
document.formname.elementname;
Now we can access these elements by:
document.firstForm.NameText
document.firstForm.AgeText
document.firstForm.PhoneText
document.firstForm.myButton1
Advantages
Using names, we can put all elements somewhere else in the
page and still have a working script, while a script using
numbers will have to be changed.
We can get the value of any textbox using the below code:
var user_input= document.firstForm.NameText.value;
If we would like to add text to textbox dynamically, we can
do this using
document.firstForm.NameText.value=”The new value”;
3. Accessing form elements using getElementById( ) method
The getElementById( ) method takes the id of HTML
element as its argument and returns a reference to that
element.
The getElementById( ) is a method of the document object
and must be written as document.getElementById( ).
With the reference we can manipulate the element in
JavaScript code.
Suppose, we have a paragraph tag defined with an id
attribute, as
<p id=”para1”>This is the paragraph.</p>
We can get a reference to the p element with the
getElementById( ) method as follows
var p_element=document.getElementById(“para1”);
The p_element is a reference to the p element identified as
“para 1” and can be used with the DOM properties.
alert(p_element.nodeName);
alert(p_element.childNodes[0].nodeValue);
Ex:
<form name=”firstForm”>
<input type=”text” id=”NameText/>
<input type=”text” id=”AgeText/>
<input type=”text” id=”PhoneText/>
<input type=”submit” id=”myButton1/>
</form>
The elements can be accessed using the below code:
var name_element=document.getElementById(“NameText”);
var age_element=document.getElementById(“AgeText”);
var phone_element=document.getElementById(“PhoneText”);
var submit_element=document.getElementById(“myButton”);
We can print the values entered in the textboxex using the code
below:
alert(document.getElementById(“NameText”).value;
alert(document.getElementById(“AgeText”).value;
alert(document.getElementById(“PhoneText”).value;
Events and Event Handling
If the user does something an event takes place.
JavaScript’s response to one of these user initiated events is called
event handling.
Different ways of registering an event handler
One of the way is assigning the event handler script to an event tag
attribute.
Ex:
<a href=”books.html” onclick=”alert(“I have clicked book
page!”)”>
alert(“I have clicked book page!”) is executed whenever the click
event takes place on this link. It is registered as an event handler.
If we want more than one statement to be executed when an event
occurs, we can create user defined function.
Ex:
<input type=”click” onclick=”myFunction( )”>
The function myFunction( ) is executed whenever the button is
submitted in the form.
a) User Interface Events
UI events deals with the transfer of focus from one object inside
the webpage to another.
Event Name Event Handler Name/ Applicable tags
Tag Attibute
Focus Onfocus <a>,<input>,<textarea>,<select>
Blur Onblur <a>,<input>,<textarea>,<select>,<button>
b) Mouse Events
JavaScript Programs have the ability to track mouse movement and
button clicks as they relate to the webpage and control.
Event Name Event Handler Name/Tag Applicable tags
Attribute
mousedown Onmousedown Most of the tags support mouse events
mouseup Onmouseup Most of the tags support mouse events
mouseover Onmouseover Most of the tags support mouse events
mousemove onmousemove Most of the tags support mouse events
mouseout Onmouseout Most of the tags support mouse events
Click Onclick Most of the tags support mouse events
Dbclick Ondbclick Most of the tags support mouse events
The mouseover and mouseout events can cause the image to
change when the mouse pointer is over the image and change back
to the original image once it leaves.
c) Key events
They are more commonly found in windows applications than in
web-based programming.
3 main key events in HTML
Event Name Event Handler Name/Tag Attribute Applicable tags
keypress onkeypress <body>,form elements
keydown onkeydown <body>,form elements
Keyup Onkeyup <body>,form elements
The keydown event occurs when almost any keyboard key has
been pressed down, including non-alphanumeric key such as
HOME, ESCAPE, INSERT and DELETE.
The keypress event, only fires when certain alphanumeric keys are
pressed, including punctuation, SPACEBAR and ENTER.
The keyup event is the complement of keydown, fires when
almost any key has been released.
d) HTML events
HTML events do not belong to UI, mouse or key event categories.
HTML events are triggered directly by a user action.
Event Event Handler Fires When Applicable
Name Name/Tag Attribute
Load onload Browser finishes <body>
loading
document.
Unload onunload Browser about to <body>
unload document
submit onsubmit Form about to be <form>
submitted
Reset onreset Form about to be <form>
reset
Select onselect Textbox contents <input>,<textarea>
selected
Change onchange Form control <input>,<textarea>,<select>
contents changed
i. Load event
The onload event handler is called when the HTML document
finishes loading into browser window.
This event is used for initialization.
ii. Unload event
The unload event fires when a browser is leaving the current
document.
This happens when the browser window is being closed or the
user has moved on to another document.
This event is used to perform cleanup tasks before the document
closes.
iii. Submit event
The submit event occurs just before a form is submitted to a
webserver.
It performs edit checking before allowing a form submission to
continue.
iv. Reset event
The reset event occurs when the reset button on a form is
clicked.
The reset button clears a form by resetting all the values back to
their defaults.
v. Select event
The select event occurs when the user selects text inside a
textbox or text area.
vi. Change event
The change event occurs when a control loses focus and its
value has been altered.
Handling Events from Body Elements
The load and unload events are the most frequently used events
in the body tag.
The onload event handler is invoked on the occurrence of a load
event, i.e., when a document is completely finished loading.
The onUnload event handler is invoked when the page is exited
or reset.
Ex:
<html>
<head>
<title>onload Event</title>
<script type=”text/javascript”>
function welcome( )
{
alert(“Welcome to our website”);
}
</script>
</head>
<body onload=”welcome( );”>
<p> This paragraph will be displayed first and then load
event will be fired</p>
</body>
</html>
Handling Events from Button Elements
The most important event associated with buttons is click event.
Some validations are performed when a user clicks on the button.
Ex:
<html>
<head>
<title>click Event </title>
<script type=”text/javascript”>
function checkAge( )
{
var enteredValue=document.getElementById(“ageField”).value;
if(enteredValue<18)
{
window.alert(“Not Eligible:Age cannot be less than 18 years”);
document.getElementById(“ageField”).value=””;
}
else{
window.alert(“you are eligible”);
}
}
</script>
</head>
<body>
<form>
<label>Enter Your Age:</label>
<input type=”text” id=”ageField”/>
<input type=”button” value=”Click here”
onclick=”ckeckAge( );”/>
</form>
</body>
</html>
Handling events from Text Box and Password elements
a. Focus and Blur Events
Onfocus is used when we give focus to an element, by clicking
on it, tabbing into it, using the tab key, or doing anything that
makes it the active element.
Onblur is used when something loses focus, by clicking on
something else, tabbing out of it, using the tab key, or doing
something that makes another element the active element.