You are on page 1of 52

Introduction to Javascript:

 JavaScript was designed to add interactivity to HTML pages


 JavaScript is a scripting language
 A scripting language is a lightweight programming language
 JavaScript is usually embedded directly into HTML pages
 JavaScript is an interpreted language (means that scripts execute without preliminary
compilation)
 Everyone can use JavaScript without purchasing a license

Comparision Between Java and Javascript:

Java and JavaScript are two completely different languages in both concept and design!

Java (developed by Sun Microsystems) is a powerful and much more complex programming
language - in the same category as C and C++.

Why Javascript?

 JavaScript gives HTML designers a programming tool - HTML authors are normally
not programmers, but JavaScript is a scripting language with a very simple syntax!
Almost anyone can put small "snippets" of code into their HTML pages
 JavaScript can put dynamic text into an HTML page - A JavaScript statement like
this: document.write("<h1>" + name + "</h1>") can write a variable text into an HTML
page
 JavaScript can react to events - A JavaScript can be set to execute when something
happens, like when a page has finished loading or when a user clicks on an HTML
element
 JavaScript can read and write HTML elements - A JavaScript can read and change the
content of an HTML element
 JavaScript can be used to validate data - A JavaScript can be used to validate form
data before it is submitted to a server. This saves the server from extra processing
 JavaScript can be used to detect the visitor's browser - A JavaScript can be used to
detect the visitor's browser, and - depending on the browser - load another page
specifically designed for that browser
 JavaScript can be used to create cookies - A JavaScript can be used to store and
retrieve information on the visitor's computer
The Real Name is ECMAScript

JavaScript's official name is ECMAScript.

ECMAScript is developed and maintained by the ECMA organization.

ECMA-262 is the official JavaScript standard.

The language was invented by Brendan Eich at Netscape (with Navigator 2.0), and has appeared
in all Netscape and Microsoft browsers since 1996.

The development of ECMA-262 started in 1996, and the first edition of was adopted by the
ECMA General Assembly in June 1997.

The standard was approved as an international ISO (ISO/IEC 16262) standard in 1998.

The development of the standard is still in progress

Basic Rules:

1. JavaScript statements end with semi-colons.


2. JavaScript is case sensitive.
3. JavaScript has two forms of comments:
o Single-line comments begin with a double slash (//).
o Multi-line comments begin with "/*" and end with "*/".

The HTML <script> tag is used to insert a JavaScript into an HTML page.

The JavaScript syntax is loosely based on the Java syntax. Java is a full blown programming
environment and JavaScript could be seen as a sub-set of the Java syntax. Having said this, that
is where the similarities end - Java and JavaScript are two totally different things.

In learning JavaScript you will become familiar with terms such as variables, functions,
statements, operators, data types, objects etc.

It will take most of this tutorial to show you the complete JavaScript syntax. For now, I'll give
you a quick intro by showing you an example and explanation.

Code:

<script type="text/javascript">
document.write("JavaScript is not Java");
</script>
This results in:

JavaScript is not Java

Points to Remember:

 The <script> tags tell the browser to expect a script in between them. You specify the
language using the type attribute. The most popular scripting language on the web is
JavaScript.
 The bits that look like HTML comments tag (<-- -->) are just that - HTML comment tags.
These are optional but recommended. They tell browsers that don't support JavaScript (or
with JavaScript disabled) to ignore the code in between. This prevents the code from
being written out to your website users.
 The part that writes the actual text is only 1 line (document.write("JavaScript is not
Java");). This is how you write text to a web page in JavaScript. This is an example of
using a JavaScript function (also known as method).

Where to put your scripts?

You can place your scripts 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 your HTML document).

How to add HTML tags to the JavaScript:

<html>
<body>
<script type="text/javascript">
document.write("<h1>Welcome To Sebiz!!!! </h1>");
</script>
</body>
</html>

This Results in:


Where to Put the JavaScript?

JavaScripts in a page will be executed immediately while the page loads into the browser. This is
not always what we want. Sometimes we want to execute a script when a page loads, or at a later
event, such as when a user clicks a button. When this is the case we put the script inside a
function, you will learn about functions in a later chapter.

Scripts in <head>

Scripts to be executed when they are called, or when an event is triggered, are placed in
functions.Put your functions in the head section, this way they are all in one place, and they do
not interfere with page content.

<html>
<head>
<script type="text/javascript">
function message()
{
alert("This alert box was called with the onload event");
}
</script>
</head>

<body onload="message()">
</body>
</html>

Scripts in <body>

If you don't want your script to be placed inside a function, or if your script should write page
content, it should be placed in the body section.

<html>
<head>
</head>
<body>
<script type="text/javascript">
document.write("This message is written by JavaScript");
</script>
</body>
</html>
Using an External JavaScript

If you want to run the same JavaScript on several pages, without having to write the same script
on every page, you can write a JavaScript in an external file.

Save the external JavaScript file with a .js file extension.

Note: The external script cannot contain the <script></script> tags!

To use the external script, point to the .js file in the "src" attribute of the <script> tag:

<html>
<head>
<script type="text/javascript" src="xxx.js"></script>
</head>
<body>
</body>
</html>

JavaScript is Case Sensitive

Unlike HTML, JavaScript is case sensitive - therefore watch your capitalization closely when
you write JavaScript statements, create or call variables, objects and functions.

JavaScript Statements

A JavaScript statement is a command to a browser. The purpose of the command is to tell the
browser what to do.

This JavaScript statement tells the browser to write "Hello Dolly" to the web page:

document.write("Hello Dolly");

It is normal to add a semicolon at the end of each executable statement. Most people think this is
a good programming practice, and most often you will see this in JavaScript examples on the
web.

The semicolon is optional (according to the JavaScript standard), and the browser is supposed to
interpret the end of the line as the end of the statement. Because of this you will often see
examples without the semicolon at the end.

Note: Using semicolons makes it possible to write multiple statements on one line.
JavaScript Variables

Variables are "containers" for storing information.Performing operations on variables that


contain values is very common and easy to do. Below is a simple script that performs all the
basic arithmetic operations. Variables are "containers" for storing information.

A variable can have a short name, like x, or a more descriptive name, like carname.

Rules for JavaScript variable names:

 Variable names are case sensitive (y and Y are two different variables)
 Variable names must begin with a letter or the underscore character

Note: Because JavaScript is case-sensitive, variable names are case-sensitive.

Declaring (Creating) JavaScript Variables

Creating variables in JavaScript is most often referred to as "declaring" variables.

You can declare JavaScript variables with the var keyword:

var x;
var carname;

After the declaration shown above, the variables are empty (they have no values yet).

However, you can also assign values to the variables when you declare them:

var x=5;
var carname="Volvo";

After the execution of the statements above, the variable x will hold the value 5, and carname
will hold the value Volvo.

Note: When you assign a text value to a variable, use quotes around the value.

Assigning Values to Undeclared JavaScript Variables

If you assign values to variables that have not yet been declared, the variables will automatically
be declared.

These statements:
x=5;
carname="Volvo";

have the same effect as:

var x=5;
var carname="Volvo";

Redeclaring JavaScript Variables

If you redeclare a JavaScript variable, it will not lose its original value.

var x=5;
var x;

After the execution of the statements above, the variable x will still have the value of 5. The
value of x is not reset (or cleared) when you redeclare it.

JavaScript Arithmetic

As with algebra, you can do arithmetic operations with JavaScript variables:

y=x-5;
z=y+5;
JavaScript Arithmetic Operators

Arithmetic operators are used to perform arithmetic between variables and/or values.

Given that y=5, the table below explains the arithmetic operators:

Operator Description Example Result


+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division remainder) x=y%2 x=1
++ Increment x=++y x=6
-- Decrement x=--y x=4
JavaScript Assignment Operators

Assignment operators are used to assign values to JavaScript variables.

Given that x=10 and y=5, the table below explains the assignment operators:

Operator Example Same As Result


= x=y x=5
+= x+=y x=x+y x=15
-= x-=y x=x-y x=5
*= x*=y x=x*y x=50
/= x/=y x=x/y x=2
%= x%=y x=x%y x=0

The + Operator Used on Strings

The + operator can also be used to add string variables or text values together.

To add two or more string variables together, use the + operator.

txt1="What a very";
txt2="nice day";
txt3=txt1+txt2;

After the execution of the statements above, the variable txt3 contains "What a verynice day".

To add a space between the two strings, insert a space into one of the strings:

txt1="What a very ";


txt2="nice day";
txt3=txt1+txt2;

or insert a space into the expression:

txt1="What a very";
txt2="nice day";
txt3=txt1+" "+txt2;

After the execution of the statements above, the variable txt3 contains:
"What a very nice day"

More Example:

<body>

<script type="text/JavaScript">

var two = 2

var ten = 10
var linebreak = "<br />"
document.write("two plus ten = ")
var result = two + ten
document.write(result)
document.write(linebreak) continued…..
document.write("ten * ten = ")
result = ten * ten
document.write(result)
document.write(linebreak)

document.write("ten / two = ")


result = ten / two
document.write(result)
</script>
</body>

This Results in:

two plus ten = 12


ten * ten = 100
ten / two = 5

Comparison Operators

Comparison operators are used in logical statements to determine equality or difference between
variables or values.

Given that x=5, the table below explains the comparison operators:
Operator Description Example

== is equal to x==8 is false

=== is exactly equal to (value and type) x===5 is true


x==="5" is false

!= is not equal x!=8 is true

> is greater than x>8 is false

< is less than x<8 is true

>= is greater than or equal to x>=8 is false

<= is less than or equal to x<=8 is true

How Can it be Used

Comparison operators can be used in conditional statements to compare values and take action
depending on the result:

if (age<18) document.write("Too young");

You will learn more about the use of conditional statements in the next chapter of this tutorial.

Logical Operators

Logical operators are used to determine the logic between variables or values.Given that x=6
and y=3, the table below explains the logical operators:

Operator Description Example

&& and (x < 10 && y > 1) is true

|| or (x==5 || y==5) is false

! not !(x==y) is true


Conditional Operator

JavaScript also contains a conditional operator that assigns a value to a variable based on some
condition.

Syntax
variablename=(condition)?value1:value2

Example
greeting=(visitor=="PRES")?"Dear President ":"Dear ";

If the variable visitor has the value of "PRES", then the variable greeting will be assigned the
value "Dear President " else it will be assigned "Dear".

More Example:

<body>
<script type="text/JavaScript">
var linebreak = "<br />"
var my_var = "Hello World!"

document.write(my_var)
document.write(linebreak)

my_var = "I am learning JavaScript!"


document.write(my_var)
document.write(linebreak)

my_var = "Script is Finishing up..."


document.write(my_var)
</script>
</body>

JavaScript If...Else Statements

In JavaScript we have the following conditional statements:

 if statement - use this statement to execute some code only if a specified condition is true
 if...else statement - use this statement to execute some code if the condition is true and
another code if the condition is false
 if...else if....else statement - use this statement to select one of many blocks of code to be
executed
 switch statement - use this statement to select one of many blocks of code to be executed

If Statement

Use the if statement to execute some code only if a specified condition is true.

Syntax
if (condition)
{
code to be executed if condition is true
}

Note that if is written in lowercase letters. Using uppercase letters (IF) will generate a JavaScript
error!

If...else Statement

Use the if....else statement to execute some code if a condition is true and another code if the
condition is not true.

Syntax
if (condition)
{
code to be executed if condition is true
}
else
{
code to be executed if condition is not true
}

Example:.

<script type="text/javascript">
//If the time is less than 10, you will get a "Good morning" greeting.
//Otherwise you will get a "Good day" greeting.

var d = new Date();


var time = d.getHours();

if (time < 10)


{
document.write("Good morning!");
}
else
{
document.write("Good day!");
}
</script>

If...else if...else Statement

Use the if....else if...else statement to select one of several blocks of code to be executed.

Syntax
if (condition1)
{
code to be executed if condition1 is true
}
else if (condition2)
{
code to be executed if condition2 is true
}
else
{
code to be executed if condition1 and condition2 are not true
}

Example

<script type="text/javascript">
var d = new Date()
var time = d.getHours()
if (time<10)
{
document.write("<b>Good morning</b>");
}
else if (time>10 && time<16)
{ continued….
document.write("<b>Good day</b>");
}
else
{
document.write("<b>Hello World!</b>");
}
</script>

JavaScript Switch Statement

Use the switch statement to select one of many blocks of code to be executed.

Syntax
switch(n)
{
case 1:
execute code block 1
break;
case 2:
execute code block 2
break;
default:
code to be executed if n is different from case 1 and 2
}

This is how it works: First we have a single expression n (most often a variable), that is
evaluated once. The value of the expression is then compared with the values for each case in the
structure. If there is a match, the block of code associated with that case is executed. Use break
to prevent the code from running into the next case automatically.

Example:

<script type="text/javascript">
//You will receive a different greeting based
//on what day it is. Note that Sunday=0,
//Monday=1, Tuesday=2, etc.

var d=new Date();


theDay=d.getDay();
switch (theDay) continued…..
{
case 5:
document.write("Finally Friday");
break;
case 6:
document.write("Super Saturday");
break;
case 0:
document.write("Sleepy Sunday");
break;
default:
document.write("I'm looking forward to this weekend!");
}
</script>

JavaScript Loops

Often when you write code, you want the same block of code to run over and over again in a
row. Instead of adding several almost equal lines in a script we can use loops to perform a task
like this.

In JavaScript, there are two different kind of loops:

 for - loops through a block of code a specified number of times


 while - loops through a block of code while a specified condition is true

The for Loop

The for loop is used when you know in advance how many times the script should run.

Syntax
for (var=startvalue;var<=endvalue;var=var+increment)
{
code to be executed
}

Example

The example below defines a loop that starts with i=0. The loop will continue to run as long as i
is less than, or equal to 5. i will increase by 1 each time the loop runs.
Note: The increment parameter could also be negative, and the <= could be any comparing
statement.

Example:

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

More Example:

<script type="text/javascript">
var linebreak = "<br />";
document.write("For loop code is beginning");
document.write(linebreak);

for(i = 0; i < 5; i++){


document.write("Counter i = " + i);
document.write(linebreak);
}

document.write("For loop code is finished!");


</script>

Results in:

For loop code is beginning


Counter i = 0
Counter i = 1
Counter i = 2
Counter i = 3
Counter i = 4
For loop code is finished!
JavaScript while loop:

The while Loop

The while loop loops through a block of code while a specified condition is true.

Syntax
while (var<=endvalue)
{
code to be executed
}

Note: The <= could be any comparing operator.

There are two key parts to a JavaScript while loop:

1. The conditional statement which must be True for the while loop's code to be executed.
2. The while loop's code that is contained in curly braces "{ and }" will be executed if the
condition is True.

When a while loop begins, the JavaScript interpreter checks if the condition statement is true. If
it is, the code between the curly braces is executed. At the end of the code segment "}", the while
loop loops back to the condition statement and begins again.

<html>
<body>
<script type="text/javascript">
var i=0;
while (i<=5)
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
</script>
</body>
</html>

More Example:

<script type="text/javascript">

var myCounter = 0; continued....


var linebreak = "<br />";

document.write("While loop is beginning");


document.write(linebreak);

while(myCounter < 10){


document.write("myCounter = " + myCounter);
document.write(linebreak);
myCounter++;
}
document.write("While loop is finished!");
</script>

Results in:
While loop is beginning
myCounter = 0
myCounter = 1
myCounter = 2
myCounter = 3
myCounter = 4
myCounter = 5
myCounter = 6
myCounter = 7
myCounter = 8
myCounter = 9
While loop is finished!

JavaScript For...In Statement

The for...in statement loops through the elements of an array or through the properties of an
object.

Syntax
for (variable in object)
{
code to be executed
}

Note: The code in the body of the for...in loop is executed once for each element/property.
Note: The variable argument can be a named variable, an array element, or a property of an
object.

Example

Use the for...in statement to loop through an array:

<html>
<body>
<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";
for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>
</body>
</html>

The do...while Loop

The do...while loop is a variant of the while loop. This loop will execute the block of code
ONCE, and then it will repeat the loop as long as the specified condition is true.

Syntax
do
{
code to be executed
}
while (var<=endvalue);

Example

The example below uses a do...while loop. The do...while loop will always be executed at least
once, even if the condition is false, because the statements are executed before the condition is
tested:
<html>
<body>
<script type="text/javascript">
var i=0;
do
{
document.write("The number is " + i);
document.write("<br />");
i++;
}
while (i<=5);
</script>
</body>
</html>

JavaScript Array

An array is a variable that can store many variables within it. Many programmers have seen
arrays in other languages, and they aren't that different in JavaScript.

Creating an array is slightly different from creating a normal variable. Because JavaScript has
variables and properties associated with arrays, you have to use a special function to create a new
array.

Example:

<script type="text/javascript">

var myArray = new Array();

myArray[0] = "Computer";
myArray[1] = "Laptop";
myArray[2] = "Notebook";

document.write(myArray[0] + myArray[1] + myArray[2]);</script>


JavaScript Array Sorting

<script type="text/javascript">
var myArray2= new Array();
myArray2[0] = "Computer";
myArray2[1] = "Laptop";
myArray2[2] = " Notebook ";

myArray2.sort();

document.write(myArray2[0] + myArray2[1] + myArray2[2]);


</script>

JavaScript Functions

A function is a piece of code that sits dormant until it is referenced or called upon to do its
"function". In addition to controllable execution, functions are also a great time saver for doing
repetitive tasks.

Instead of having to type out the code every time you want something done, you can simply call
the function multiple times to get the same effect. This benefit is also known as "code
reusability".

A function that does not execute when a page loads should be placed inside the head of your
HTML document.

To keep the browser from executing a script when the page loads, you can put your script into a
function.

A function contains code that will be executed by an event or by a call to the function.

You may call a function from anywhere within a page (or even from other pages if the function
is embedded in an external .js file).

Functions can be defined both in the <head> and in the <body> section of a document. However,
to assure that a function is read/loaded by the browser before it is called, it could be wise to put
functions in the <head> section.
How to Define a Function

Syntax
function functionname(var1,var2,...,varX)
{
some code
}

The parameters var1, var2, etc. are variables or values passed into the function. The { and the }
defines the start and end of the function.

Note: A function with no parameters must include the parentheses () after the function name.

Note: Do not forget about the importance of capitals in JavaScript! The word function must be
written in lowercase letters, otherwise a JavaScript error occurs! Also note that you must call a
function with the exact same capitals as in the function name.

JavaScript Function Example

<html>
<head>
<script type="text/javascript">
function displaymessage()
{
alert("Hello World!");
}
</script>
</head>

<body>
<form>
<input type="button" value="Click me!" onclick="displaymessage()" />
</form>
</body>
</html>

If the line: alert("Hello world!!") in the example above had not been put within a function, it
would have been executed as soon as the page was loaded. Now, the script is not executed before
a user hits the input button. The function displaymessage() will be executed if the input button is
clicked.
The return Statement

The return statement is used to specify the value that is returned from the function.So, functions
that are going to return a value must use the return statement.

The example below returns the product of two numbers (a and b):

<html>
<head>
<script type="text/javascript">
function product(a,b)
{
return a*b;
}
</script>
</head>

<body>
<script type="text/javascript">
document.write(product(4,3));
</script>

</body>
</html>

The Lifetime of JavaScript Variables

If you declare a variable within a function, the variable can only be accessed within that function.
When you exit the function, the variable is destroyed. These variables are called local variables.
You can have local variables with the same name in different functions, because each is
recognized only by the function in which it is declared.

If you declare a variable outside a function, all the functions on your page can access it.
The lifetime of these variables starts when they are declared, and ends when the page is
closed.

JavaScript Popup Boxes

JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

Types of Popups
Alert Box

An alert box is often used if you want to make sure information comes through to the user

.When an alert box pops up, the user will have to click "OK" to proceed.

Syntax
alert("sometext");

Example:

<html>
<head>
<script type="text/javascript">
function popup() {
alert("Hi students!!!")
}
</script>
</head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>

Results in:
Confirm Box

A confirm box is often used if you want the user to verify or accept something.

When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.

Syntax
confirm("sometext");

Asks the user to confirm something.Example:

<html>

<head>

<script type="text/javascript">

function showconfirm(){

var t=confirm("Press any button!");

if (t==true)

alert("You pressed OK!");


}

else

alert("You pressed Cancel!");

}}</script>

</head>

<body>

<input type="button" onclick="showconfirm()" value="Show" />

</body>

</html>

Results in:

Prompt Box

Prompts the user for information. A small dialogue box pops up and appears in front of the web
page currently in focus.
The confirm box is different from the alert box. It supplies the user with a choice; they can either
press OK to confirm the popup's message or they can press cancel and not agree to the popup's
request.

Syntax
prompt("sometext","defaultvalue");

Example below:

<head>

<script type="text/javascript">

function show_prompt() {

var reply = prompt("Hey! What's your name?", "")

alert ( "Nice to see you " + reply + "!") continued……

}</script>

</head>

<body>

<input type="button" onclick="show_prompt()" value="show prompt!">

</body>

Results in:
After clicking OK, alert box will get open.

JavaScript Print Script

The JavaScript print function window.print() will print the current webpage when executed.

<form>
<input type="button" value="Print This Page" onClick="window.print()" />
</form>

Results in:
JavaScript Window.Location

Control over what page is loaded into the browser rests in the JavaScript property
window.location. By setting window.location equal to a new URL, you will in turn change the
current webpage to the one that is specified.

Example:

<script type="text/javascript">
window.location = "http://www.google.com/"
</script>
JavaScript String Length

Advanced scripters will often need to know how long a JavaScript string is. For example, if a
web developer was creating a submission form that required the username to be no longer than
20 characters, then she would need to check the length of the string before allowing the user to
submit data.

The length property returns the number of characters that are in a string, using an integer.

<script type="text/javascript">

var t = "Richard";

var length = t.length;

document.write("The string is this long: " + length);

document.write("<br />The string is this long: " + t.length);

</script>

Results in:

Split Function:

<script type="text/javascript">
var myString = "123456789";

var mySplitResult = myString.split("5");

document.write("The first element is " + mySplitResult[0]);


document.write("<br /> The second element is " + mySplitResult[1]);
</script>

Results in:

The first element is 1234


The second element is 6789
String Search Function

This string function takes a regular expression and then examines that string to see if there are
any matches for that expression. If there is a match , it will return the position in the string where
the match was found. If there isn't a match, it will return -1.

Example:

<script type="text/javascript">

var myRegExp ="John";

var string1 = "Today John went to the store and talked with Alex.";

var matchPos1 = string1.search(myRegExp);

if(matchPos1 != -1)

document.write("There was a match at position " + matchPos1);

else

document.write("There was no match in the first string");

</script>

Results in:

String indexOf Function

IndexOf has two arguments, with the second one being optional:

1. SearchString - What you would like to search for.


2. Offset (optional) - How far into the string you would like the search to begin. If you want
to search the whole string, omit this argument.
<script type="text/javascript">

var a = "He is playing";

var aPosition = a.indexOf("is");

document.write("The position = " + aPosition);

</script>

Results in:

JavaScript getElementById:

If you want to quickly access the value of an HTML input give it an id to make your life
a lot easier. This small script below will check to see if there is any text in the text field
"myText". The argument that getElementById requires is the id of the HTML element you wish
to utilize.

<script type="text/javascript">
function notEmpty(){
var myTextField = document.getElementById('myText');
if(myTextField.value != "")
alert("You entered: " + myTextField.value)
else
alert("Would you please enter some text?")
}
</script>
<input type='text' id='myText' />
<input type='button' onclick='notEmpty()' value='Submit’/>
Results in:

JavaScript innerHTML

Each HTML element has an innerHTML property that defines both the HTML code and the text
that occurs between that element's opening and closing tag. By changing an element's
innerHTML after some user interaction, you can make much more interactive pages.

However, using innerHTML requires some preparation if you want to be able to use it easily and
reliably. First, you must give the element you wish to change an id.

With that id in place you will be able to use the getElementById function, which works on all
browsers.

<script type="text/javascript">

function changeText(){

document.getElementById('boldStuff').innerHTML = 'Priya';

</script>

<p>Welcome <b id='boldStuff'>People!!!</b> </p>

<input type='button' onclick='changeText()' value='Change Text'/>


JavaScript Date Today

<h4>It is now
<script type="text/javascript">
var currentTime = new Date()
</script>
</h4>

Get the JavaScript Time

The Date object has been created, and now we have a variable that holds the current date! To get
the information we need to print out, we have to utilize some or all of the following functions:

 getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM


 getSeconds() - Number of seconds (0-59)
 getMinutes() - Number of minutes (0-59)
 getHours() - Number of hours (0-23)
 getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday
 getDate() - Day of the month (0-31)
 getMonth() - Number of month (0-11)
 getFullYear() - The four digit year (1970-9999)

Example 1:

<h4>It is now
<script type="text/javascript">
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
document.write(month + "/" + day + "/" + year)
</script>
</h4>

Example 2:

<h4>It is now
<script type="text/javascript">
var currentTime = new Date()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
if (minutes < 10){
minutes = "0" + minutes
}
document.write(hours + ":" + minutes + " ")
if(hours > 11){
document.write("PM")
} else {
document.write("AM")
}
</script>
</h4>

Javascript Events

By using JavaScript, we have the ability to create dynamic web pages. Events are actions that
can be detected by JavaScript.

Every element on a web page has certain events which can trigger a JavaScript. For example, we
can use the onClick event of a button element to indicate that a function will run when a user
clicks on the button. We define the events in the HTML tags.

Example containing all the events:


<script type="text/javascript" language="JavaScript">

function handler(t,c,s)
{
t.value += s;
c.checked = true;
return 0
}

</script>

<form name="formA" action="javascript:void(0)"


onreset= "handler(formB.t1, formB.reset, 'reset')"
onsubmit="handler(formB.t1, formB.submit, 'submit')">

<textarea rows="4" cols="45" wrap="soft"


onclick= "handler(formB.t1, formB.click, 'click ')"
ondblclick= "handler(formB.t1, formB.dblclick, 'dblclick ')"
onmouseover="handler(formB.t1, formB.over, 'over ')"
onmouseout= "handler(formB.t1, formB.out, 'out ')"
onmousemove="handler(formB.t2, formB.move, '+')"
onfocus= "handler(formB.t1, formB.focus, 'focus ')"
onblur= "handler(formB.t1, formB.blur, 'blur ')"
onkeydown= "handler(formB.t1, formB.keydown, 'keydown ')"
onkeyup= "handler(formB.t1, formB.keyup, 'keyup ')"
onkeypress= "handler(formB.t1, formB.keypress, 'keypress ')"
onchange= "handler(formB.t1, formB.change, 'change ')"
onselect= "handler(formB.t1, formB.select, 'select ')">
Move the mouse, click and type here. Try selecting text.
</textarea>
<input type="Reset"> <input type="Submit" value="Submit">
</form>

<form name="formB">
<!-- Event Handler Output: -->
<textarea name="t1" rows="8" cols="45" wrap="soft"></textarea>
<textarea name="t2" rows="8" cols="10" wrap="soft"></textarea>
click:<input type="checkbox" name="click">
dblclick:<input type="checkbox" name="dblclick">
over:<input type="checkbox" name="over">
out:<input type="checkbox" name="out">
move:<input type="checkbox" name="move">
focus:<input type="checkbox" name="focus">
keydown:<input type="checkbox" name="keydown">
keyup:<input type="checkbox" name="keyup">

select:<input type="checkbox" name="select">


keypress:<input type="checkbox" name="keypress">
<!-- additional checkboxes not shown... -->
</form>

JavaScript Void(0)

Sometimes, you may need to call some JavaSript from within a link. Normally, when you click a
link, the browser loads a new page (or refreshes the same page).

This might not always be desirable. For example, you might only want to dynamically update a
form field when the user clicks a link.

To prevent the load from refreshing, you could use the JavaScript void() function and pass a
parameter of 0 (zero).

Math Object:

Example:
<html>

<script type="text/javascript">

document.write(Math.E);

document.write("<br/>");

document.write(Math.PI)

document.write("<br/>");

document.write(Math.SQRT2)

document.write("<br/>");

document.write(Math.SQRT1_2)

document.write("<br/>");

document.write(Math.LN2)

document.write("<br/>");

document.write(Math.LN10)

document.write("<br/>");

document.write(Math.LOG2E)

document.write("<br/>");

document.write(Math.LOG10E);

document.write("<br/>");

document.write(Math.pow(10,2));

document.write("<br/>");

document.write(Math.sqrt(169));

document.write("<br/>");

with (Math)
{

var x= sin(3.5)

var y=tan(5)

var result=max(x,y)

document.write(result);

</script>

</html>

This Results in:

round()
How to use round().

random()
How to use random() to return a random number between 0 and 1.

max()
How to use max() to return the number with the highest value of two specified numbers.
min()
How to use min() to return the number with the lowest value of two specified numbers.

<html>

<body><script type="text/javascript">

document.write(Math.round(0.60) + "<br />");

document.write(Math.random() + "<br />");

document.write(Math.max(5,10) + "<br />");

document.write(Math.min(5,10) + "<br />");

</script></body>

</html>

JavaScript Browser Detection


The Navigator object contains information about the visitor's browser.

There are some things that just don't work on certain browsers - especially on older browsers.

Sometimes it can be useful to detect the visitor's browser, and then serve the appropriate
information.

The best way to do this is to make your web pages smart enough to look one way to some
browsers and another way to other browsers.

The Navigator object contains information about the visitor's browser name, version, and more

<html>
<body>
<script type="text/javascript">
document.write("Browser CodeName: " + navigator.appCodeName);
document.write("<br /><br />");
document.write("Browser Name: " + navigator.appName);
document.write("<br /><br />");
document.write("Browser Version: " + navigator.appVersion);
document.write("<br /><br />");
document.write("Cookies Enabled: " + navigator.cookieEnabled);
document.write("<br /><br />");
document.write("Platform: " + navigator.platform);
document.write("<br /><br />");
document.write("User-agent header: " + navigator.userAgent);
</script>

</body>
</html>

JavaScript Try...Catch Statement


The try...catch statement allows you to test a block of code for errors.

The try block contains the code to be run, and the catch block contains the code to be executed if
an error occurs.

Example:

<html>
<head>
<script type="text/javascript">
var txt="";
function givemessage()
{
try
{
adddlert("Welcome to sebiz!");
}
catch(err)
{
txt="There was an error on this page.\n\n";
txt+="Error description: " + err.description + "\n\n";
txt+="Click OK to continue.\n\n";
alert(txt);
}
}
</script>
</head>
<body>
<input type="button" value="View" onclick="givemessage()" />
</body>

</html>

The Throw Statement

The throw statement allows you to create an exception. If you use this statement together with
the try...catch statement, you can control program flow and generate accurate error messages.

<html>
<body>
<script type="text/javascript">
var x=prompt("Enter a number between 0 and 10:","");
try
{
if(x>10)
{
throw "Err1";
}
else if(x<0)
{
throw "Err2";
}
else if(isNaN(x))
{
throw "Err3";
}
}
catch(er)
{
if(er=="Err1")
{
alert("Error! The value is too high");
}
if(er=="Err2")
{
alert("Error! The value is too low");
}
if(er=="Err3")
{
alert("Error! The value is not a number");
}
}
</script>
</body>
</html>

In JavaScript you can add special characters to a text string by using the backslash sign.

Insert Special Characters

The backslash (\) is used to insert apostrophes, new lines, quotes, and other special characters
into a text string.

JavaScript Cookies

Cookies are small text files that sit on your hard disk. Cookies are created when you visit
websites that use cookies to store information that they need (or prefer). Websites often use
cookies to personalise the user experience - such as remembering your name (assuming you
supplied it previously) or remembering the items in your shopping cart from previous visits.

Despite the many misconceptions about cookies being malicious, they are quite harmless.
Cookies can't give your personal details to other websites, or transmit a virus or anything like
that. A cookie can only be read by the server that created it. Websites normally use cookies to
make its users' lives easier, not harder.

Creating Cookies in JavaScript

document.cookie =
"myContents=Quackit JavaScript cookie experiment;
expires=Fri, 19 Oct 2007 12:00:00 UTC; path=/";

Now check your cookies folder to see if the cookie was created. Alternatively, write code to read
the cookie.
Note: If the cookie wasn't created, check the expiry date - it needs to be a date in the future.

You can update this value by using the same code with a different value. If you want to add a
second value, simply use a different variable name (for example "myContents2=").

Reading Cookies in JavaScript

document.write(document.cookie);

You simply reference the cookie using document.cookie. The only problem with the above code
is that it outputs the equals sign and everything before it (i.e. "myContents="). To stop this from
happening, try the following code:

document.write(document.cookie.split("=")[1])

Deleting Cookies in JavaScript

To delete a cookie, you can use the same code you used to create it but this time, set the expiry
date in the past:

document.cookie =
"myContents=Quackit JavaScript cookie experiment;
expires=Fri, 14 Oct 2005 12:00:00 UTC; path=/";

//for creating a cookie


<script type="text/javascript">
var today = new Date();
var nextMonth = new Date(today.getYear(), today.getMonth()+1, today.getDate());
setCookie("technofundoDemoCookie", "Manish", nextMonth);
</script>

JavaScript Status Bar Messages


JavaScript can be used to display messages in the status bar using window.status. For example,
you can display a javascript status bar message whenever your users hover over your hyperlinks.

<a href="a.html"
onMouseover="JavaScript:window.status='Status Bar Message goes here'; return true"
onMouseout="JavaScript:window.status=''; return true">Hover over me!</a>

Most (newer) major browsers disable status bar messages by default. If your status bar doesn't
change when you hover over the link, it's probably because of this.
If you really want to see this example, you can enable status bar messages by changing your
browser settings.

For example, in Firefox:

1. Go to Tools > Options


2. Click the Content tab
3. Ensure that the JavaScript option is checked
4. Click Advanced (next to the Enable JavaScript option)
5. Check the Change status bar text option
6. Click OK to save this screen
7. Click OK again

In Internet Explorer:

1. Go to Tools > Internet Options


2. Click the Security tab
3. Ensure that the Internet option is selected/highlighted
4. Click Custom Level... (this launches the security settings for the Internet zone)
5. Scroll down until you see Allow status bar updates via script (under the Scripting
option). Click Enable
6. Click OK to save this screen
7. Click OK again

Note that, because this is the default setting in most browsers, there's a good chance that most of
your users won't see your status bar message

JavaScript Form Validation

The idea behind JavaScript form validation is to provide a method to check the user entered
information before they can even submit it. JavaScript also lets you display helpful alerts to
inform the user what information they have entered incorrectly and how they can fix it. In this
lesson we will be reviewing some basic form validation, showing you how to check for the
following:

 If a text input is empty or not


 If a text input is all numbers
 If a text input is all letters
 If a text input is all alphanumeric characters (numbers & letters)
 If a text input has the correct number of characters in it (useful when restricting the length
of a username and/or password)
 If a selection has been made from an HTML select input (the drop down selector)
 If an email address is valid
 How to check all above when the user has completed filling out the form
Form Validation - Checking for Non-Empty
<script type='text/javascript'>
function notEmpty(elem, helperMsg){
if(elem.value.length == 0){
alert(helperMsg);
elem.focus();
return false;
}
return true;
}
</script>
<form>
Required Field: <input type='text' id='req1'/>
<input type='button'
onclick="notEmpty(document.getElementById('req1'), 'Please Enter a Value')"
value='Check Field' />
</form>

Form Validation - Checking for All Numbers


<script type='text/javascript'>
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>
<form>
Numbers Only: <input type='text' id='numbers'/>
<input type='button'
onclick="isNumeric(document.getElementById('numbers'), 'Numbers Only Please')"
value='Check Field' />
</form>

Form Validation - Checking for All Letters

function isAlphabet(elem, helperMsg){


var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

Form Validation - Restricting the Length


function lengthRestriction(elem, min, max){
var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}

Form Validation - Selection Made


<script type='text/javascript'>
function madeSelection(elem, helperMsg){
if(elem.value == "Please Choose"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}
</script>
<form>
Selection: <select id='selection'>
<option>Please Choose</option>
<option>CA</option>
<option>WI</option>
<option>XX</option>
</select>
<input type='button'
onclick="madeSelection(document.getElementById('selection'), 'Please Choose
Something')"
value='Check Field' />
</form>

Full Form Validation:

<script type='text/javascript'>

function formValidator(){
// Make quick references to our fields
var firstname = document.getElementById('firstname');
var addr = document.getElementById('addr');
var zip = document.getElementById('zip');
var state = document.getElementById('state');
var username = document.getElementById('username');
var email = document.getElementById('email');

// Check each input in the order that it appears in the form!


if(isAlphabet(firstname, "Please enter only letters for your name")){
if(isAlphanumeric(addr, "Numbers and Letters Only for Address")){
if(isNumeric(zip, "Please enter a valid zip code")){
if(madeSelection(state, "Please Choose a State")){
if(lengthRestriction(username, 6, 8)){
if(emailValidator(email, "Please enter a
valid email address")){
return true;
}
}
}
}
}
}

return false;

function notEmpty(elem, helperMsg){


if(elem.value.length == 0){
alert(helperMsg);
elem.focus(); // set the focus to this input
return false;
}
return true;
}
function isNumeric(elem, helperMsg){
var numericExpression = /^[0-9]+$/;
if(elem.value.match(numericExpression)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function isAlphabet(elem, helperMsg){


var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function isAlphanumeric(elem, helperMsg){


var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}

function lengthRestriction(elem, min, max){


var uInput = elem.value;
if(uInput.length >= min && uInput.length <= max){
return true;
}else{
alert("Please enter between " +min+ " and " +max+ " characters");
elem.focus();
return false;
}
}

function madeSelection(elem, helperMsg){


if(elem.value == "Please Choose"){
alert(helperMsg);
elem.focus();
return false;
}else{
return true;
}
}

function emailValidator(elem, helperMsg){


var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
if(elem.value.match(emailExp)){
return true;
}else{
alert(helperMsg);
elem.focus();
return false;
}
}
</script>

<form onsubmit='return formValidator()' >


First Name: <input type='text' id='firstname' /><br />
Address: <input type='text' id='addr' /><br />
Zip Code: <input type='text' id='zip' /><br />
State: <select id='state'>
<option>Please Choose</option>
<option>AL</option>
<option>CA</option>
<option>TX</option>
<option>WI</option>
</select><br />
Username(6-8 characters): <input type='text' id='username' /><br />
Email: <input type='text' id='email' /><br />
<input type='submit' value='Check Form' />
</form>
JavaScript Timing Events

JavaScript can be executed in time-intervals.

This is called timing events.

JavaScript Timing Events

With JavaScript, it is possible to execute some code after a specified time-interval. This is called
timing events.

It's very easy to time events in JavaScript. The two key methods that are used are:

 setTimeout() - executes a code some time in the future


 clearTimeout() - cancels the setTimeout()

Note: The setTimeout() and clearTimeout() are both methods of the HTML DOM Window
object

The setTimeout() method returns a value - In the statement above, the value is stored in a
variable called t. If you want to cancel this setTimeout(), you can refer to it using the variable
name.

The first parameter of setTimeout() is a string that contains a JavaScript statement. This
statement could be a statement like "alert('5 seconds!')" or a call to a function, like "alertMsg()".

The second parameter indicates how many milliseconds from now you want to execute the first
parameter.

There are 1000 milliseconds in one second.

SetTimeOut Example:

<html>
<head>
<script type="text/javascript">
function timedMsg()
{
var t=setTimeout("alert('5 seconds!')",5000);
}
</script>
</head>

<body>
<form>
<input type="button" value="Display timed alertbox!"
onClick="timedMsg()" />
</form>
</body>
</html>

ClearTime Out Example:

<html>
<head>
<script type="text/javascript">
var c=0;
var t;
var timer_is_on=0;

function timedCount()
{
document.getElementById('txt').value=c;
c=c+1;
t=setTimeout("timedCount()",1000);
}

function doTimer()
{
if (!timer_is_on)
{
timer_is_on=1;
timedCount();
}
}

function stopCount()
{
clearTimeout(t);
timer_is_on=0;
}
</script>
</head>

<body>
<form>
<input type="button" value="Start count!" onClick="doTimer()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
</body>
</html>

You might also like