About Tutorials ?: What These Tutorials Contain?
About Tutorials ?: What These Tutorials Contain?
Introduction
In these tutorials I am intended to concentrate on the fundamentals of the JavaScript.
I will cover all the objects, functions of the JavaScript. After completing this tutorials you will be
able to write JavaScript programs, call JavaScript functions , able to call JavaScript from one
page to other page and able to call JavaScript in Server side .
I assume that Reader doesnt have any programming knowledge and if the reader have
programming knowledge on C or C++ then JavaScript would be quite easy for him/her to learn.
Readers who read these tutorials are recommended to have some HTML knowledge.
If you are not familiar with HTML, visit HTML section of tutorials .
Those who are hunger to learn JavaScript , have the food!
what is JavaScript?
JavaScript is a Scripting language that usually placed in HTML pages. It can also be termed as
extension to HTML. Its initially introduced as Live Script and renamed as JavaScript. So we can
say that prior to JavaScript, Live Script has come. In other words Java Script is the advanced
version of live Script. It has been introduced by Sun Microsystems and Netscape.
Is it similar to Java?
Now the question arises is whether it is similar to Java?
Peers! Dont ever get perplexed with Java and Java Script.
Java Script is much easier than Java.
Java vs JavaScript
Java is a high level Programming language and Java Script is the Client side Scripting
language.
Java is used to develop applications, but JavaScript is used to develop some kind of
functionalities like Validations on client side in web forms or web pages.
Its a Client side Scripting language that is embedded in HTML tags and can also be used at
Server side too.
How is it Useful?
Its mainly useful in developing client side scripting in WebPages .
Go to browser's View menu and click on source. So you are able to see all the client side code
.Right!
JavaScript allows us to perform calculations, validate web forms, change the design or
background of the page, create cookies, detect browsers, add special effects, and customize
graphics selections so that interactive features of page can be improved.
<html>
<head>
<h2>Math Object demo</h2>
<script type="text/javascript">
alert("Absolute: "+ Math.abs(-2))
alert("PI: " + Math.PI)
alert("cos: " + Math.cos(0) )
</script>
</head>
<body></body>
</html>
In a similer mannar we can work with other functions of the math object too.
Understanding Events
This article explains about Javascript Events and their use
JavaScript comes with wide variety of events that are helpful in solving real world
scenarios.The interesting thing in JavaScript is to create dynamic web pages that
enhance user interaction.Javascript events help in building interactive web pages.
An event is defined as an item that fires based on action.
Commonly used events in JavaScript are:
onclick
onload
onmouseover
onkeypress
Here is simple example for Javascript click event. We are trying to fire a message in
an alert box when the button is clicked.
1. Create FireMsg method in the script tag based on the technical requirement.
Here we need to place the code related to the action that is performed when a
button is clicked
In this case we are just trying to fire a message in alert box. You may try for user Id
and password validation as an assignment
2. Assign this method in onclick event of the button.
<html>
<head>
<script type="text/javascript">
<!-function FireMsg()
{
alert("Button Clicked")
}
//-->
</script>
</head>
<body>
<input type="button" value="Click Me!" onclick="FireMsg()"><br />
</body>
Execution:
The way it executes is simple and straight forward. When user clicks on button it
fires the corresponding event and the functionality related to that event is executed.
So simple !!
Javascript myths
1. It is not similar to Java
2. An IDE like Visual Interdev /Visual Studio are not required for scripting
3. Its not Object oriented Language
4. It doesn't manage the memory
<html>
<body>
<script text =javascript">
document.write("Welcome to DotnetSpider Tutorials!");
</script>
</body>
</html>
To run it:
Like how you run a simple HTML program just double click on the First.html Or Right click on
the mouse and click on browse.
Now your first JavaScript Program is displayed on browser.
Formatted text
This article explains about writing more formatted Text in HTML tags using Java Script
Friends ,Now let's have one more step ahead and try to write the text in a beautiful
format that is acceptable by client.
<html>
<body>
<script >
document.write("<b>Welcome to DotnetSpider Tutorials!</b>");
</script>
</body>
</html>
Just ! Guess what would be the output ? Yeah ! You are Right!
The output will be the text that is composed in document.write. But the thing that
is additional here is it would display in bold as follows in the browser.
Welcome to DotnetSpider Tutorials!
alert
In general what do we mean by the term alert? Its a kind of attention to something
that we are aware or not aware. JavaScript alert is used to display a message box
kind of box and show a customized message that is given by the user. Generally it's
used to show a user friendly message to the user after certain validation depending
on the business logic. We can't change the title bar of the alert box, or OK
button that comes with alert box . Clicking on OK it returns nothing, but simply
closes the alert box.
confirm
JavaScript confirm is a confirmation box mainly used for client side validations such
as to warn a user about something such that are ' you sure do you want to
proceed' or Are you sure you want to delete the item? etc.
It comes with OK and Cancel buttons. If we click on OK it returns true.If we click
on Cancel it returns false.
prompt
Javascript prompt is used to allow the user to enter something. We can capture the
entered value.
If you are familiar with C programming what I can compare is alert is something like
printf and prompt is like scanf.
<html>
<body>
<script language=text/javascript">
window.alert("Welcome to Dotnetspider Tutorails");
</script>
</body>
</html>
So the output in the browser would be an alert box with Welcome to dotnetspider tutorials
What will happen if you don't specify any arguments in the alert method? Does it give an Error?
Just check and see.
Well, it doesn't give any error but you will get an alert box but no message is shown since we
didn't specify any message.
Note: Please don't forget to place the message in double quotes. Otherwise you will get an error
as JavaScript is case sensitive. Another point here its our choice to use single quotes or double
quotes in an alert box while quoting text.
The only part of an alert box you have control over is the text.
JavaScript confirm
As mentioned earlier confirm is used for choosing an option from two choices. It will return a
Boolean value. Lets have a look at the example.
<html>
<body>
<script type="text/javascript">
var v=window.confirm("Are you sure you are ok?");
window.alert(v);
</script>
</body>
</html>
prompt
<html>
<body>
<script type="text/javascript">
var v=window.prompt("Enter the Number","10");
window.alert(v);
</script>
</body>
</html>
Out put here is self explanatory. We get a prompt dialog box that takes input in prompt box.
The given input is captured or stored in variable v. Value of v is displayed in an alert message.
Here Enter the Number in prompt box title and 10 is the default value.
Just try with by giving window. prompt (); with our any parameters. JavaScript prompt doesnt
specify any default values neither it contains title. So in order to beautify our code its
recommended to use proper and customized title in all of the boxes.
<body>
<script type="text/javascript">
var v=window.prompt("Enter your rating from 1 to 10 scale in JavaScript");
</script>
</body>
JavaScript function needs to be assigned to event. We place event in html tag of the control itself.
For example onclick event fires when we click on that control by any cast.
Some of the commonly used events are:
onclick
onblur
onchange
onkeypress
onmouseover
onselect
onsubmit
onfocus
Onclick
This event is applicable to controls like button, radio button, check box, submit button etc.
<html>
<head>
<script>
function f()
{
alert('Hello! How are you?');
}
</script>
</head>
<body>
<input type ="button" value ="Click" onclick ="return f();" >
</body>
else
{
alert("successfully logged in");
window.open("Welcome.html");
}
}
</script>
</head>
<body>
UserId : <input type="text" id="uid">
<br/>
Passowrd: <input type="text" id="pwd">
<br /><br/>
<input type ="button" onclick="f()" value ="LogIn">
</body>
</html>
Explanation:
When we don't enter anything in palce of userid it gives a message that userid can't be blank.
The same is the case with password field.
When ever user press on login button then click event gets fired, it makes a call to function f() .
The code in f () is executed.
document.getElementById () is use to identify the control that is given as parameter. Pass Id of
the control as parameter.
We are checking for the value whether the control is empty or not.
document.getElementById (ctrlId).value indicates value of that is corresponds to that
control. We are validating in such that if nothing is entered corresponding message is fired.
When we enter userid and password in textbox it goes to a page Welcome.html but since the page
is not there you will get an error as page cant be displayed in Popup. To avoid this type we need
to have Welcome.html in the same folder where Login.html is saved.
Add the following HTML code:
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<P> <h1> Welome to Home Page </h1> </P>
</body>
</html>
<html>
<head>
<script src="ExternalFile.js"></script>
</head>
<body>
</body>
</html>
Advantages?
1.Reusability since dont need to place the code in HTML documents.
2.If there is a kind of change in validation then we dont need to change code in all webpages.
3. It secures precious code.
Go to view ?source in browser your validation code cant be seen .
Example
Type the following code in note pad and save with extension as .js (external.js)
function f()
{
External.Html
<html>
<head>
<script src ="external.js"></script>
</head>
<body>
<input type = "button" value ="click" onclick ="f();">
</body>
</html>
Execution
When ever a button is clicked it checks for the function in script tag. Control goes to source tag
and calls external.js file. In that file it checks for the function f(). The corresponding coding in f()
is displayed in browser. So the same script can be called in different we pages .Many functions
can be placed in JavaScript external file.
If a script is defining functions that are used by some other functions, then it is better to define it
before use.
JavaScript Objects
This article explains introduction to JavaScript objects
Object
An object is collection of properties and methods. For example in our real world book is an
object .It s collection of pages. It has parts like pages, Cover. It composes of methods like Open
() and close (). Here properties and methods related to single object called book.
Window object is the base object to all JavaScript Objects.
Document object is inherited from window object.
We can create our own objects in JavaScript but most of the time we use built in objects only.
JavaScript supports several built-in objects .These are defined for the developer in order to work
with WebPages, compute and access the Web browser.
Some of the mainly used objects are:
String
Date
Math
Array
Object.
String Object:
String is nothing but a piece of text. The purpose of string object is to work over text. This is
most commonly used object. String object has only one property called length . This returns
length of the string.
Syntax:
string.length where string is the variable of type string.
Example
<html>
<head>
<title>JavaScript Tutorials</title>
</head>
<body>
The lengh of the string is :
<script language ="JavaScript">
var v="Dotnet Spider";
document.write(v.length);
</script>
</body>
</html>
output
The above example shows output in browser as The lengh of the string is : 13
var v="Dotnet Spider"; creates a string called V and stores the specified text as Dotnet Spider.
The length of the string is computed using length property .As the string length is 13 it's
displayed on browser.
<html>
<head>
<script>
function f()
{
v =document.getElementById('txt');
alert(v.value.length);
}
</script>
</head>
<body>
Enter Text and click on button to get lengh:<BR>
<input type ="text" id ="txt">
<input type ="button" value ="Click" onclick ="return f();" >
</body>
</HTML>
The output is self explanatory. It takes the input string and calculates the lengh.
The main purpose of length validation in real time is used in following cases.
To check length of password field, minimum as 7 characters maximum 25
To check Userid length id the length is not in the specified range and fire validation message
To force user to enter in textboxes when it's a mandatory field or any other fields length
checking
Example
day
day
day
day
=
=
=
=
new
new
new
new
Date()
Date("August15, 2006 08:25:00")
Date(06,8,15)
Date(06,8,15,8,25,0)
Methods
getHours() - Returns the hour
getMinutes() - Returns the minutes
getDate()
Returns the day of the month in a specified Date.
<html>
<head>
<script>
function f()
{
var date = new Date()
document.write(date.getDate())
}
</script>
</head>
<body>
<input type ="button" value ="Click to get today's day" onclick ="return f();"
>
</body>
As getDate returns current day between 1 to 31 , the above code produces today's
day as output.
Note that it returns date of client not server.
getMonth()
returns current month code of current Date or month code of specified date.
<html>
<head>
<script>
function f()
{
var date = new Date ("August 21, 2006 01:15:00")
document.write(date.getMonth()+1)
}
</script>
</head>
<body>
<input type ="button" value ="Click to get month" onclick ="return f();" >
</body>
As get month returns an integer between 0 and 11, it will return 7 for August month
In order to get correct results we increment it by 1 .We get output as 8.
getYear()
returns current year or year of specified date if year is specified.
<html>
<head>
<script>
function f()
{
var date = new Date ()
alert("Specified Year is "+ date.getYear("August 15 , 2006 01:17:00"))
}
</script>
</head>
<body>
<input type ="button" value ="Click to get year " onclick ="return f();" >
</body>
Note
getFullYear()Gets 4digits year ,where as getYear() returns 2 digits by default and
depending on date specified it may return 4 digits too.
Array object
This article explains JavaScript Array object
Array
In simple words Array is collection of similar datatypes. Array index starts from 0.
Instead of declaring many variables for different strings or other data types, we can
store it as a collection in an Array.
Defining an Array
Regular array
We declare array and assign in next statement.
var myArray = new Array(5)
Now in order to assign elements to Array
myArray[0]=Hima
myArray[1]=Sandhya
myArray[2]=Sujatha
Here length of the array is 5.
Condensed array
Here declaration and assignment can be done in a single statement
var myArray=new Array("Hima", "Sandhya", "Sujatha")
Literal array
Here we dont use new key word to create an array. Directly we declare and assign.
This is one type of declaring and assigning.
var myArray=["Hima", "Sandhya", "Sujatha"]
Index for Hima would be 0, String Sandhya is stored in 1st index and Sujatha is
stored in 2nd position .
Now we can refer the element Sujatha as myArray[3]
Methods
concat()
Syntax: Array.concat(arrayName2, arrayName3, ..., arrayNameN)
Joins two or more arrays and returns the result .
join()
Syntax : Array.join(separator)
Puts all the elements of an array into a string. The elements are separated by a
specified delimiter like ,
pop()
Removes and returns the last element of an array .This will effect length of the
array.
Syntax: Array.pop()
push()
Adds one or more elements to the end of an array and returns the new length. This
will effect length of the arrary.
Syntax: Array.push()
reverse()
Reverses the order of the elements in an array
Syntax: Array.reverse()
shift()
Removes and returns the first element of an array
Syntax: Array.shift() .This may effect length of the array.
slice()
Returns selected elements from an existing array
Syntax: Array.slice(begin[,end])
sort()
This sorts the elements of an array
Syntax: Array.sort(compareFunction)
splice()
Removes and adds new elements to an array
toSource()
Represents the source code of an object. This is inhertied from Object
Syntax: Array.toSource()
toString()
Converts an array to a string and returns the result .
Syntax: Array.unshift(element1,..., elementN)
unshift()
Adds one or more elements to the beginning of an array and returns the new
length.This effects lengh of an array.
Syntax: Array.unshift(element1,..., elementN)
valueOf()
Returns the primitive value of an Array object. This is derived from Object
Syntax: Array.valueOf()
exp
exp(a) returns e to the power of a
floor
floor(x) rounds the passed value down to the next lowest integer.
ex: floor(3.74) results as 3
log
log(x) returns the natural logarithm (base E) of x
max
max(a,b) returns the larger value of a or b.
ex: Math.max(5,7) results as 7
min
min(a,b) returns the smaller value of a or b.
ex: Math.min(5,7) results as 5
pow
pow(a,b) returns the value of a to the power b
ex: Math.pow(5,2) results as 25
random
random(a,b) returns a random number between 0 and 1
round
round(a) returns the value of a to the nearest integer.
ex: Math.round(5.2) results as 5
sqrt
sqrt(a) returns the value of square root of a
ex: Math.sqrt(25) results as 5
<html>
<head>
<h2>Math Object demo</h2>
<script type="text/javascript">
alert("Absolute: "+ Math.abs(-2))
alert("PI: " + Math.PI)
alert("cos: " + Math.cos(0) )
</script>
</head>
<body></body>
</html>
In a similer mannar we can work with other functions of the math object too.
boolean object is defined using new keyword .It is used to convert a non-boolean
value to a boolean value (true or false).
boolVar=new
boolVar=new
boolVar=new
boolVar=new
boolVar=new
boolVar=new
Boolean()
Boolean(0)
Boolean(null)
Boolean("")
Boolean(false)
Boolean(NaN)
All the below lines of code assigns boolean objects with an initial value of true:
var
var
var
var
boolVar=new
boolVar=new
boolVar=new
boolVar=new
Boolean(true)
Boolean("true")
Boolean("false")
Boolean("Richard")
<html>
<head>
<script type="text/javascript">
</script>
</head>
<body></body>
</html>
Understanding Events
This article explains about Javascript Events and their use
JavaScript comes with wide variety of events that are helpful in solving real world
scenarios.The interesting thing in JavaScript is to create dynamic web pages that
enhance user interaction.Javascript events help in building interactive web pages.
An event is defined as an item that fires based on action.
Commonly used events in JavaScript are:
onclick
onload
onmouseover
onkeypress
Here is simple example for Javascript click event. We are trying to fire a message in
an alert box when the button is clicked.
1. Create FireMsg method in the script tag based on the technical requirement.
Here we need to place the code related to the action that is performed when a
button is clicked
In this case we are just trying to fire a message in alert box. You may try for user Id
and password validation as an assignment
2. Assign this method in onclick event of the button.
<html>
<head>
<script type="text/javascript">
<!--
function FireMsg()
{
alert("Button Clicked")
}
//-->
</script>
</head>
<body>
<input type="button" value="Click Me!" onclick="FireMsg()"><br />
</body>
Execution:
The way it executes is simple and straight forward. When user clicks on button it
fires the corresponding event and the functionality related to that event is executed.
So simple !!
</script>
</head>
<body onbeforeunload="close()">
<a href="microsoft.com"> Click Here to navigate to Microsoft</a>
</body>
</html>
Note:
The default statement that appears in the dialog box, "Are you sure you want to
navigate away from this page? ... Press OK to continue, or Cancel to stay on the
current page.", cannot be removed or altered.