Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

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 .

The Proposed Readers


This tutorial is mainly written for beginners and technical enthusiasts those who wanted to learn
by them self. If the pillar is strong, then the building would be. So if you are strong enough in
basics then you can write complex business logic as well. Right!

Why these tutorials?


The main purpose of these tutorials is to learn the JavaScript by yourself with out having to go to
an Instructor. You may not get proper time or convenient transportation to go to an instructor and
learn. People will have knowledge, but when they dont have proper guidance, so they are in
trouble .More over you have to spend some specific time to do get taught by some one. I hope
that these tutorials guide students and beginners to learn by themselves.

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 do you mean by JavaScript?


All about JavaScript?

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.

It is also called Object Oriented Language, where as JavaScript is Object based.

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.

Is it Client Side Scripting or Server Side?

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.

Math Object - Example


This article explains about JavaScript math Object
Let's have a look at simple example that deals working with some of the math
object 's functions.

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

Important points to make a note about


JavaScript
Points to ponder:
Here is some important facts about JavaScript. This will give you some idea about JavaScript
and other scripting languages:
1. JavaScript is a Client side scripting language
2. It supports all browsers
3. Its easy to learn
4. Its interpreted language
5. Its generally embedded or placed in HTML tags
6. It can respond to events
7. Its not Object oriented Its object based
8. Its more Interactive and dynamic.
9. Its interpreted but not compiled
10. Its weakly typed

11. It's Case sensitive

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

Our first JavaScript program


First.Html
Let us write a simple HTML page and learn how to embed Javascript in the HTML pages.
This is a simple program , just displays text message that is given by the user.
Type the following code in notepad or copy and paste it in the note pad.

<html>
<body>
<script text =javascript">
document.write("Welcome to DotnetSpider Tutorials!");
</script>
</body>
</html>

Create a folder called JavaScript in D: Drive

Save the code that is written in notepad as First.Html


A file with extension .html is created.
The purpose of <script text =javascript"> to tell the browser that it is JavaScript.
On the other hand document.write is used to write the output for the page.
What ever the text that is given in the that is executed.
Ending the statements with ; is not mandatory. Its developer choice to omit or use.
But how ever semicolons are needed if we want to write more than one statement on a single
line. But it is always a good practice to make our code as readable and beautify it proper
indentation . So it's suggested to seperate the multiple statements ,instead of clubbing all the
statements in a single line.

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!

More HTML formats in the SCRIPT


Simple program in a more formatted way.
Let us take one more example so that inserting HTML code in the text would be more easy.
We can insert all the formats that HTML supports in JavaScript.
<html>
<body>
<script text =javascript">
document.write("<h1> <p align = 'center' ><i>Javascript Tutorials
</i></p></h1>");
document.write("<p align = 'center'><font color = 'red'> Welcome to
DotnetSpider Tutorials!</font></p>");
</script>
</body>
</html>

Output in the browser

Javacript popup objects!


This article explains three important commands of the JavaScript window object
This chapter briefs the window object important functions and their usage.
JavaScript window object
Window Object has several methods and Events that will be used in JavaScript.
An event is something that responds to certain actions or a function.
A method is something that may or may not take arguments but have some
functionality defined in it. When the method is called then functionality related to
that method is processed. We declare some methods through Javascript and call
corresponding methods in the Event. That will be easily understood in the coming
chapters.
alert, confirm, prompt

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.

More practical Approach


This article explains practical approach that we have learned in previous chapter
Well, Let us write an example that shows an alert message from browser.
So, how to proceed it?
Yes. Its quite simple. Just place the message that needs to be displayed in alert box in double
quotes.

The same ' Welcome to Spider ' in an alert


box

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

Working with confirm and prompt


This article explains usage of the confirm and prompt in Javascript

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>

Have you observed the fact? Right!


If you are clicked on OK it returns true so value of v is true. If you are clicked on Cancel it
returns false so value of v is false, that is displayed dynamically on an alert box based on the
click.
Here did you notice the thing that is new var v. Yeah this is how we declare variables in
JavaScript.
var v;
And assignment as follows:
v = 10;
We can even combine declaration and assignment in a single statement. That can be
var v = 10;
Note: Remember JavaScript is case sensitive. The variable v is different from variable V.
Variable declaration in JavaScript is optional. That is if we don't declare a variable it takes as
variable type by default.

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.

prompt, confirm ,alert all together


This article explains usage of alert ,prompt,confirm
Let's put all together with some conditional statement in one example and proceed
further.

<body>
<script type="text/javascript">
var v=window.prompt("Enter your rating from 1 to 10 scale in JavaScript");

confirm("Are you sure you want to see the rating");


if(v>5)
alert('Good');
else if(v==5)
alert('Moderate');
else
alert('Poor');

</script>
</body>

Here if is a conditional statement that checks value of v. If v is greater than 5 then


an alert message is fired with message as Good.
If v is equals to 5 then corresponding message is fired.
Apart from above two cases for all the other a message box with message Poor is
displayed.
Note
Script tag can be placed in Header or body but if you want to place it in the body
you need to mention language = JavaScript . But in header its an optional since it
take JavaScript in Body by default
I think now you are confident enough on alert, confirm, prompt.
Let's move on to the next chapter then...

Calling JavaScript function in an Event


This article explains about calling a simple Java script function in an event .
Let's write a simple Javascript function and make it to fire on click event of command button.
Event is something that can respond to particular action.
Each HTML control has got certain kind of events which can fires JavaScript functions. That

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>

Execution of the Page:


When alert.html is executed form is loaded with a command button. Until and unless JavaScript
function is called it doesnt get executed. Here we have assigned f () for onclick. So JavaScript
function is called as soon as we click on the button and the code in the function is executed.
Hence we click on button an alert box is executed.

A simple login Validation with JavaScript


This article explains a simple JavaScript validation
Here is an example of simple login page client side validation.
Save this as Login.html
<html>
<head>
<script>
function f()
{
if(document.getElementById('uid').value.length==0)
alert("UserId can't be blank");
else if(document.getElementById('pwd').value.length==0)
alert("Password can't be blank");

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>

save this as Welcome.html

Calling JavaScript from some other page


This article explains about calling Javascript from an external file.
JavaScript that is in other files is called external JavaScript.
External JavaScript can be called using src attribute of script tag.
Syntax as follows:

<html>

<head>
<script src="ExternalFile.js"></script>
</head>
<body>
</body>
</html>

Where this is exactly fit in real time?


If you want to do a required field validation (making to enter/select for particular control as
mandatory) for 10 pages, what you will do probably. The same validation needs to be fired in 10
webpages. We can avoid this by using calling external script.

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()
{

alert(calling External JavaScript);


}

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.

Where to Use script in the body or header?


A <script src="url"></script> blocks the downloading of other page components until the script
has been identified, compiled, and executed. So It is better to call for the script as late as
possible. If there are images or other components that will not be delayed. So it is usually best to
make all <script src="url"></script> the last features before the </body>.

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.

For complete listing of JavaScript objects refer JavaScriptObject Hierarchy

The JavaScript String object

This article explains about String object into depth.

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.

The string Object


This article explains about JavaScript 'String 'object

<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

The Date Object


This article explains about the JavaScript Date object
The other important JavaScript object is Date Object. In order to work with date and time its
used. As all of us know that JavaScript is a client side language and the script runs on the client,
therefore it will always return the date/time of the client. You can use date object to display a
"countdown," such as the number of days left
for the favorite movie to release .
Instantiating Date Object can be done on either of these ways.
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds) //most parameters here are
optional. Not specifying causes 0 to be passed in.

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

getSeconds() - Returns the seconds


getYear() - Returns the year ("06" is 2006)
getMonth() - Returns the month ( returns "0" is if month is January)
getDate() - Returns the day of the month
getDay() - Returns the day of the week ( returns "0" is if week is Sunday)

Date object's' getDate() method


This article explains about Date object getDate() method

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.

Javascript date object's getMonth()


This article explains date object's getMonth() method

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.

JavaScript Date object's getYear()


This article explains about JavaScript Date object's getYear() method

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>

As getYear() returns year out put is 2006

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]

Array Object methods


This article explains about JavaScript Array Object methods

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

The Math Object


This article explains about JavaScript MathObject
The JavaScript math object can be called without creating a new object for it.
The JavaScript Math object is used to compute common mathematical calculations.
It includes several mathematical functions that can help in mathematical
calculations.
Methods
Here are some important methods about Javascript Math Object
abs
abs(a) Returns absolute value of a.
ex: Math.abs(-2) results as 2
acos
acos(a) returns cosine of a in radians
ex: Math.acos(0) results as 1
asin
asin(a) returns cosine of a in radians
ex: Math.asin(0) results as 0
atan
acos(a) returns tan of a in radians
ex: Math.tan(0) results as 0
atan2
atan2(b,a)returns counterclockwise angle between x axis and point (b,a).
ceil
ceil(a) - rounds up the value of "a" to the next integer.
ex: ceil(3.14) results as 3

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

Math Object - Example

This article explains about JavaScript Math object


Let's have a look at simple example that deals working with some of the math
object 's functions.

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

The Boolean Object


This article explains about JavaScript Boolean Object
Boolean is a primitive data type in JavaScript that holds the entity either true or
false.
We can say Boolean object as a package or wrapper for boolean value. Dont get
confuse with boolean data type and boolean object.

boolean object is defined using new keyword .It is used to convert a non-boolean
value to a boolean value (true or false).

Defining a boolean object


syntax: var boolVar=new Boolean()
The above code defines new Boolean object.
If we pass no intial value, 0, -0, null,"" false, undefined or NAN then it will evaluate
to false. Otherwise its true. But remember that if we pass this value to an if
condition then it will return true.
That is for example
All the below lines of code create boolean objects with an initial value of false:
var
var
var
var
var
var

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

Boolean Object - An Example


This article explains an example that shows boolean object 's creation
Now lets try to implement things that we have learned from previous chapter
Save following sample code as bool .html and run in the browser to understand the
basic differences for boolean object arguments .

<html>
<head>
<script type="text/javascript">

document.write("<br/>When double quotes passed ---</br> ")


document.write( b = new Boolean("") + "<br/>")
document.write("<br/>When nothing is passed --- </br>")
document.write(b = new Boolean() + "<br/>")
document.write("<br/>When false is passed --- </br> ")
document.write(b = new Boolean(false) + "<br/>")
document.write("<br/>When NAN is passed ---</br> ")
document.write(b = new Boolean(NaN) + "<br/>")
document.write("<br/>When nulll is passed --- <br/>" )
document.write(b = new Boolean(null) + "<br/>")
document.write("<br/>When undefined is passed ---<br/> ")
document.write(b = new Boolean(undefined) + "<br/>")
document.write("<br/>When 0 is passed --- <br/>")
document.write(b = new Boolean(0) + "<br/>")
document.write("<br/>When true with quotes passed---<br/> ")
document.write(b = new Boolean("true") + "<br/>")
document.write("<br/>When false with quotes passed ---<br/>")
document.write(b = new Boolean("false") + "<br/>")
document.write("<br/>When true passed --- <br/>")
document.write(b = new Boolean(true) + "<br/>")

document.write("<br/>When 1 is passed --- <br/>")


document.write(b = new Boolean(1) + "<br/>")

</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 !!

Playing with window events


This article explains about onbeforeunloadevent
The approach
There are some cases where you might want to instruct the user before he/She is
navigating to the next page. That might be a meaningful message like "Are you sure
you want to navigate away from the current page?"
Probably end user pressed the X button by mistake and he/she might loose his/her
current state
There is onbeforeunload event for the JavaScript that fires when you are navigating
away from the current page.
Here is the Code for that.
<html>
<head>
<script type="text/javascript">
function close()
{
event.returnValue = "This will navigate to next page.";
}

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

How to call JavaScript from code behind?


This article explains calling Javascript from Codebehind
Many a times I see repeatedly asked question in forums is how do we call Javascript
from codebehind?
<script>
function Test()
{
alert('Calling this function in Codebehind')
}
</script>
In order to call Test() in page_load event of codebehind file ,I mean Cs /vb file
Button1.Attributes.Add("onclick", " return Test();");
This will call Javascript from serverside when the corresponding event is fired.
Javascript in codebehond
To Use confirm message directly from codebehind
btnSubmit.Attributes.Add("onclick", "if(!confirm('Are you sure?')) return false;")

You might also like