Unit 4 JAVA SCRIPT
Unit 4 JAVA SCRIPT
Unit 4 JAVA SCRIPT
1
JavaScript
JavaScript is a dynamic computer programming
language. It is lightweight and most commonly used as a
part of web pages, whose implementations allow client-
side script to interact with the user and make dynamic
pages. It is an interpreted programming language with
object-oriented capabilities.
2
JavaScript has been around for several years now, in many different flavors. The main
benefit of Javascript is to add additional interaction between the web site and its visitors
at the cost of a little extra work by the web developer. Javascript allows industrious web
masters to get more out of their website than HTML and CSS can provide.
3
By definition, Javascript is a client-side scripting language. This means the web surfer's browser
will be running the script. This is opposite to client-side is server-side, which occurs in a
language like PHP. These PHP scripts are run by the web hosting server.
There are many uses (and abuses!) for the powerful Javascript language. Here are a few things
that you may or may not have seen in your web surfing days.
4
Example of java scripts:
Clocks
Mouse Trailers (an animation that follows your mouse when you surf a site)
Drop Down Menus
Alert Messages
Popup Windows
Html form Data Validation
5
Advantages of JavaScript
Less server interaction − You can validate user input before sending
the page off to the server. This saves server traffic, which means less
load on your server.
<script ...>
JavaScript code
</script>
The script tag takes two important attributes −
Language − This attribute specifies what scripting language you are using.
Typically, its value will be javascript. Although recent versions of HTML (and
XHTML, its successor) have phased out the use of this attribute.
So the identifiers Time and TIME will convey different meanings in JavaScript.
Comments in JavaScript
JavaScript supports both C-style and C++-style comments, Thus −
• Any text between a // and the end of a line is treated as a comment and is ignored
by JavaScript.
• Any text between the characters /* and */ is treated as a comment. This may span
multiple lines.
• JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript
treats this as a single-line comment, just as it does the // comment.
/*
* This is a multi-line comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
</script>
How To Write Javascript
If you have ever used CSS before, then the whole part about how to include
Javascript will be a lot simpler to grasp. Here are three important steps you
should always take when creating or using someone else's Javascript code.
12
Use the script tag to tell the browser you are using Javascript.
Write or download some Javascript
Test the script!
There are so many different things that can go wrong with a script, be it human error, browser compatability issues, or operating system
differences. So whenever using Javascript, be sure that you test your script out on a wide variety of systems and most importantly,
different web browsers.
13
Your First Javascript Script
To follow the classic examples of many programming let's use Javascript to print out "Hello
World" to the browser. I know this isn't very interesting, but it will be a good way to explain all
the overhead required to do something in Javascript
14
HTML & JavaScript Code:
<html>
<body>
<script type="text/javascript">
document.write("Hello World!")
</script>
</body>
</html>
15
Our first step was to tell the browser we were using a
script with <script> tag. Next we set the type of script
equal to "text/javascript", which you may notice that
doing this is similar to the way you specify CSS, which
is "text/css".
Next we added an optional HTML comment that
surrounds our Javascript code. If a browser does not
support Javascript, then it will not display our code in
plain text to the user! The comment was ended with a
"//-->" because "//" signifies a comment in Javascript,
so we add that to prevent a browser from reading the
end of the HTML comment in as a piece of Javascript
code.
16
Javascript document.write
The final step of our script was to use a function called document.write which writes a string into our
HTML document. document.write can be used to write text, HTML, or a little of both. We passed the
famous string of text to the function to spell out "Hello World!" which it printed to the screen.
17
Syntax
Looking at our Javascript code above, notice that there is no semicolon at the end of the statement "document.write(Hello World!)".
Why? Because Javascript does not require that you use semicolons to signify the end of each statement.
If you are an experienced programmer and prefer to use semicolons, feel free to do so. Javascript will not malfunction from ending
semicolons. The only time it is necessary to use a semicolon is when you choose to smash two statements onto one line(i.e. two
document.write statements on one line).
18
Javascript - Is it Enabled?
This lesson will first teach you how to enable Javascript in Internet Explorer then show you how
you can write a very simple script to separate those who don't have Javascript enabled from
those that do on your websites.
19
Enable Javascript - Internet Explorer
In Internet Explorer 6/7 (download Internet Explorer) you can check to see if Javascript is enabled by navigating to the custom security settings that are somewhat buried (don't worry we'll help you find it).
Click on the Tools menu
Choose the Internet Options... from the menu
Click the Security tab on the Internet Options pop up
Click the Custom Level... button to access your security settings
Scroll almost all the way down to the Scripting section
Select the Enable button for Active scripting
Click OK to finish the process
Click Yes when asked to confirm
20
Javascript Detection
These days it's basically impossible to navigate the web without a Javascript enabled browser, so checking whether
or not a user has Javascript enabled is not all that important. Chances are the only way it be disabled is if the
company's IT staff has decided to disable Javascript for some reason. However, if you still want to be sure your
users are Javascript enabled, this script will get it done
21
The only sure fire way to separate users that
don't have Javascript from those that do is to
use a simple redirect script that will only work
for those with Javascript enabled. If a person's
browser does not have Javascript enabled the
script will not run and they will remain on the
same page.
22
Javascript Code:
23
Where to Place Javascript
There are three general areas that Javascript can be
placed for use in a web page.
24
Inside the head tag
Within the body tag
In an external file
The location choice of head or body is very simple. If you want to have a script run on some event, such as when a user clicks
somewhere, then you will place that script in the head. If you want the script to run when the page loads, like our "Hello World!"
example , then you will want to place the script within the body tag.
25
An Example Head Script
Since we have already seen the kind of script that goes in the body, how about we
write a script that takes place when some event occurs, say a click on a button.
26
HTML & JavaScript Code:
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("Hello World!")
}
</script> </head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>
27
28
29
We created a function called popup and placed it in the head of the HTML
document. Now every time someone clicks on the button (this is an event)
"Hello World!“ will be display. We will go into more depth on functions and
events in a later .
30
External Javascript Files
Having already dicussed placing Javascript in the head and body of your HTML
document, let us now explore the third possible location, an external file.
31
Importing an External Javascript File
Importing an external file is relatively painless. First the file you are importing must be valid Javascript, and only Javascript.
Second, the file must have the extension ".js". Lastly, you must know the location of the file.
Let us assume we have a file "myjs.js" that contains a one line Hello World alert function. Also, let us assume that the file is the
same directory as our HTML file we are going to code up. To import the file you would do the following in your HTML document.
32
HTML & JavaScript Code:
<html>
<head>
<script src="myjs.js">
</script>
</head>
<body> <input type="button" onclick="popup()" value="Click Me!">
</body>
</html>
33
function popup()
{
document.write("Hello World!")
}
myjs.js
34
35
36
37
Great Javascript Repositories
There is a ton of great stuff you can do with Javascript, if you know how to code like Paul Allen and Bill Gates, but for the rest of us it is
nice to get incredible Javascript tools without having to write them ourselves. Below are some of the better Javascript resources on the
web these days.
JavaFile.com
Java-Scripts.com
38
External File Tips & Recap
Use external Javascript files when you want to use the same script on many pages, but don't want to have to rewrite the code on every page!
Use external Javascript files for including both types of scripts! The type that you place in the head (functions) and the type you place in the
body (scripts you want to run when the page loads).
Be sure that your Javascript files (.js) do not include the <script> tag. They should only have the HTML comment and Javascript code.
39
Javascript Operators
Operators in Javascript are very similar to operators that appear in other programming languages.
The definition of an operator is a symbol that is used to perform an operation. Most often these
operations are arithmetic (addition, subtraction, etc), but not always.
40
Javascript Arithmetic Operator Chart
41
Operator English Example
+ Addition 2+4
- Subtraction 6-2
* Multiplication 5*3
/ Division 15 / 3
% Modulus 43 % 10
42
Assignment operator
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
Javascript Operator Example with Variables
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
44
<html>
<body>
<script type="text/javascript">
var two=2
var ten=10
document.write("two + ten = ")
result=two + ten
document.write(result)
</script>
</body>
<html>
45
46
<html>
<body>
<script type="text/javascript">
var two=2
var ten=10
document.write("two - ten = ")
result=two - ten
document.write(result)
</script>
</body>
<html>
47
48
Comparison Operators
Comparisons are used to check the relationship between variables and/or values. A single equal sign sets a value
while a double equal sign (==) compares two values. Comparison operators are used inside conditional statements
and evaluate to either true or false.
49
Operator English Example Result
== Equal To x == y false
!= Not Equal To x != y true
< Less Than x<y true
> Greater Than x>y false
<= Less Than or Equal To x <= y true
50
Logical operator
Operator Description
Operator Description
Variables in Javascript behave the same as variables in most popular programming languages
(C, C++, etc) except that you don't have to declare variables before you use them. If you don't
know what declaring is, don't worry about it, it isn't important!
54
Javascript Using Variables
A variable's purpose is to store information so that it can be used later. A variable is a symbolic name that
represents some data that you set. To think of a variable name in real world terms, picture that the name is a
grocery bag and the data it represents are the groceries. The name wraps up the data so you can move it around a
lot easier, but the name is not the data!
55
A Variable Example
When using a variable for the first time it is not necessary to use "var" before the variable name, but it is
a good programming practice to make it crystal clear when a variable is being used for the first time in
the program. Here we are showing how the same variable can take on different values throughout a script
56
<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>
57
58
We made two variables in this example. One to hold the HTML for a line break and the other was a dynamic variable that had a total
of three different values throughout the script.
To assign a value to a variable you use the equal sign (=) with the variable on the left and the value to be assigned on the right. If you
swap the order then your script will not work correctly! In english the Javascript "myVar = 'Hello World!'" would be: myVar equals
'Hello World!'.
The first time we used a variable we placed var in front to signify its first use. In subsequent assignments of the same variable we did
not need the var.
59
Javascript Variable Naming Conventions
When choosing a variable name you must first be sure that you do not use any of the Javascript reserved
names . Another good practice is choosing variable names that are descriptive of what the variable holds. If you
have a variable that holds the size of a shoe, then name it "shoe_size" to make your Javascript more readable.
60
Finally, Javascript variable names may not start with a numeral (0-9). These variable names
would be illegal: 7lucky, 99bottlesofbeer, and 3zacharm.
A good rule of thumb is to have your variable names start with a lowercase letter (a-z) and use
underscores to separate a name with multiple words (i.e. my_var, strong_man, happy_coder,
etc).
61
Javascript Functions
If you have any programming experience, then you do not need to spend much time on this . Functions in
Javascript behave similar to numerous programming languages (C, C++, PHP, etc). If this is your first time learning
about functions, then be sure to go through this very thoroughly as a solid understanding of functions will make
the rest of this easier to follow
62
What's a Function?
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 repeatable 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”
63
Example Function in Javascript
A function does not execute when the page loads and so it should be placed inside the head of your
HTML document. Creating a function is really quite easy, all you have to do is tell the browser you're
making a function, give the function a name, and then write the Javascript like normal.
64
HTML & JavaScript Code:
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("Hello World!")
}
</script> </head>
<body>
<input type="button" onclick="popup()" value="popup">
</body>
</html>
65
We first told the browser we were going to be using a function by typing "function". Next, we
gave our function a name, so that we could use it later. Since we are making a pop up , we
called our function "popup".
The curly braces "{,}" define the boundaries of our function code. All popup function code must
be contained within the curly braces.
66
What we didn't talk about was how we got this function to execute when the
button is clicked. The click is called an event, and we will be talking about
how to make functions execute from various types of events in the next
lesson.
67
Writing Your Own Function
You can also make your own functions to be used on your webpage. If you would
like to write your own function then you must use the special keyword function
68
Events in Javascript
The absolute coolest thing about Javascript is the ability to create dynamic web pages that increase
user interaction, making the visitor feel like the website is almost coming alive right before their eyes.
69
The building blocks of an interactive web page is the Javascript event system. An event in Javascript is something that happens with or on the web page. A few example of
events:
A mouse click
The web page loading
Mousing over a hot spot on the web page, also known as hovering
Selecting an input box in an HTML form
A keystroke
70
A Couple of Examples Using Events
Javascript has predefined names that cover numerous events that can occur, including the ones listed above.
To capture an event and make something happen when that event occurs you must specify the event, the
HTML element that will be waiting for the event, and the function(s) that will be run when the event occurs.
71
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("hello")
} </script>
</head>
<body>
<input type="button" value="Click Me!" onclick="popup()">
<br />
<a href="#" onmouseover="popup()" > Hover Me!</a>
</body>
</html>
72
73
74
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("hello")
} </script>
</head>
<body>
<input type="button" value="Click Me!" onclick="popup()">
<br />
<a href="#" onmouseout="popup()" > Hover Me!</a>
</body>
</html>
75
76
77
With the button we used the event onClick event as our desired action and told it to call our popup function
that is defined in our header. To call a function you must give the function name followed up with
parenthesis "()".
Our mouseover and mouseout events were combined on one HTML element, a link. We wanted to do nothing
when someone put their mouse on the link, but when the mouse leaves (onMouseout) we displayed a popup.
78
<html>
<head>
<script type="text/javascript">
function popup()
{
document.write("hello")
}
</script>
</head>
<body>
<input type="button" value="Click Me!" onmouseout="popup()">
<br />
</body>
</html>
79
80
81
82
Javascript Statements
All the Javascript code that you will write will, for the most part, be comprised of many separate
statements. A statement is setting a variable equal to a value. A statement is also a function call,
i.e. document.write(). Statements define what the script will do and how it will be done.
83
Typical Ending of a Statement
84
Categories of Statements
In addition to the standard statements like changing a variable's value, assigning a new value, or calling a function, there are groups of statements that are distinct in their
purpose. We will provide a brief overview of each of these categories .
Conditional Statements
Loop Statements
Object Manipulation Statements
Comment Statements
Exception Handling Statements
85
Conditional Statements
If you were to win a 100 la Rs lottery then you would probably quit your job. That last statement
is a conditional if/then statement that is used a great deal in programming. If some condition
(winning the lottery) is true, then something happens (you quit your job). If the condition is
false, then you probably will not take that action (quit your job).
86
Conditional statements are used to control your scripts so that different actions can be taken
depending on the situation. You may want to display a special image on your home page during
the holidays. This condition would depend on what day it was, and if it was a holiday, then a
special holiday image would be displayed to your visitors. Without proper knowledge of the
conditional statement your scripts will not be as lively or dynamic as they could possibly be.
87
Loop Statements
Have you ever had to send out marriage announcements? If not, this is how it goes. You take the invitation, place it in the
envelope, lick the envelope, seal the envelope, then send it off. Then you take the next invitation off the stack of 99
remaining invitations, place it in an envelope, lick the envelope, seal... You get the idea! It is a boring, repetitive task!
Wouldn't it be great if there was an easier way? Well in programming and in Javascript there is. The process is called
"looping" and it will turn your cute little scripts into massive work horses with the right planning
88
A loop statement checks to see if some condition is true, say our condition is "Are there any invitations left?"
and if that condition is true it will execute a chunk of code. Our code in this example would be to stuff, lick,
and seal the envelope. After the code is executed the condition is checked again, if it is true then the
process begins again, if it is false, then the loop code stops execution and the script continues along.
Believe me when I say this is something you want to learn more about!
89
Object Manipulation Statements
These are statements that are used to take advantage of the object model to get tasks done. If
you do not know about the object model at this time, do not worry. We will be talking about it
later.
90
Comment Statements
Comment statements are used to prevent the browser from executing certain parts of code that you designate as non-
code. Why would you want to do this? There are many reasons. By disallowing the block of text to be read you can
then place in comments for yourself, much like HTML comments, and you can also block out segments of your code for
whatever reason you may have.
The single line comment is just two slashes (//) and the multiple line comment starts with (/*) and ends with (*/).
91
Exception Handling Statements
Sometimes when you are programming you do not know for sure if the file that you will be writing to, the input stream you are
reading from, or the connection you have established will be usable for the code that you want to execute. There is a way to program
safety mechanisms, so that your code handles common problems that may arise (maybe the input stream you are reading from
suddenly disappears).
The try...catch statement tries to execute a piece of code and if it fails the catch should handle the error gracefully. This is an
advanced programming subject that is interesting, but not necessary for the majority of Javascript programmers.
92
Javascript If Statement
As your Javascript programs get more sophisticated you will need to make use of conditional
statements that allow your program to make decisions. Nearly all other programming languages
use conditionals and Javascript is no exception.
93
The If Statement is a way to make decisions based on a variable or some other
type of data. For example you might have a variable that stores the date. With
this tiny bit of information you could easily program a small script to print out
"Today is my Birthday!" whenever the day and month were equal to your birthday
94
Javascript If Statement Syntax
There are two major parts to an if statement: the conditional statement and the code to be executed.
The conditional statement is a statement that will evaluate to either True or False. The most common type of a
conditional statement used is checking to see if something equals a value. An example would be checking if the date
equaled your birthday.
95
The code to be executed contains the Javascript code that will be executed
only if the If Statement's conditional statement was true. In this simple If
Statement example we print out a message if the variable we are checking is
equal to 7.
96
<html>
<body>
<script type="text/javascript">
var myNum = 7
if(myNum == 7)
{
document.write("Lucky 7!")
}
</script>
</body>html>
97
98
This simple example created myNum and set it to 7. We then checked to see if myNum was
equal to 7 "myNum == 7" in the If Statement's conditional statement which evaluated to True.
Because the conditional statement was True the block of code associated with our If
Statement "document.write..." was executed, as you can see in the Display.
99
Javascript If Statement: Else
We already taught you how to execute code if a given condition is True, but what if you want to execute another
piece of code if something is False? The answer is to use an extension to the If Statement; the Else clause.
The Else clause is executed when the conditional statement is False. Let's take our example from above, add an
Else clause and change the value of myNum so that our conditional statement is False.
100
<html>
<script type="text/javascript">
var myNum = 10;
if(myNum == 7){ document.write("Lucky 7!"); }
else{
document.write("You're not very lucky today...");
} </script>
</html>
101
102
<html>
<script type="text/javascript">
var visitor = "principal“
if(visitor == "teacher")
{ document.write("My dog ate my homework..."); }
else
if(visitor == "principal"){ document.write(“hello principal"); } else { document.write("How do you do?"); }
</script></html>
103
104
There are two important things to note about the Else If extension:
You must have a normal If Statement before you can use the Else If statement. This is because the Else If statement
is an addon to the If Statement.
You can have multiple Else If add-ons. In our example we only used one Else If extension, but you can add as many as
you require.
105
Javascript While Loop
The while loop is an advanced programming technique that allows you to do something over and
over while a conditional statement is true. Although the general uses of the while loop are usually
a bit complex, this lesson will teach you the basics of how to create a while loop in Javascript
106
Javascript While Loop Explained
There are two key parts to a Javascript while loop:
The conditional statement which must be True for the while loop's code to be executed.
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 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.
If the condition statement is always True then you will never exit the while loop, so be very careful when using while loops
107
Creating a Simple While Loop
This example shows how to create a basic while loop that will execute
a document.write 10 times and then exit the loop statement.
108
<html>
<script type="text/javascript">
var myCounter = 0;
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> </html>
109
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!
110
Our variable myCounter started off at 0, which is less than 10, so our while loop executed its code. The value 0 was printed to the
browser and then myCounter was incremented by 1 and the while loop started over again.
1 was less than 10 so the while loop's code was executed...and the process repeats itself a few more times until...
myCounter was 10 which was not less than 10 so the while loop's code did not execute. You can see this in the Display: because the
last value to be printed out was 9.
Note: Advanced programmers may recognize that a for loop would be a better solution for this example, but we hope you can ignore
this for our needs to create an easy example!
111
Javascript For Loop Explained
There are four important aspects of a Javascript for loop:
The counter variable is something that is created and usually used only in the for loop to count how many times the for loop has looped.
The conditional statement that decides whether the for loop continues executing or not. This check usually includes the counter variable in some way.
The counter variable is incremented after every loop in the increment section of the for loop.
The code that is executed for each loop through the for loop.
This may seem strange, but 1-3 all occur on the same line of code. This is because the for loop is such a standardized programming practice that the
designers felt they might as well save some space and clutter when creating the for loop.
112
<html>
<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></html>
113
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!
114
The counter variable name i may seem a little strange, but it has
been used for years now that you might as well get used to it as
the default for loop counter. Other common variable names are j,
k, x and y
So in this example our counter was initially set to 0 with "i = 0;"
and then the conditional statement "i < 5;" was executed. Our
counter was indeed smaller than 5 and so the for loop's code was
executed.
After the loop's code had been executed then the increment "i++"
happens, making the counter i equal to 1. The for loop then
checked that i was less than 5, which it was, resulting in the
loop's code being executed again.
This looping happened a couple more times until i was equal to 5,
which is not less than 5 and the for loop stopped executing.
For loops may seem very confusing at first, but let me assure you,
they are quite useful and should be studied thoroughly by anyone
who wishes to become a intermediate programmer.
115
Javascript Comments
Have you ever written a script or a program in the past only to look at it 6 months later and
have no idea what's going on in the code? You probably forgot to do what all programmers tend
to forget: write comments!
116
When writing code you may have some complex logic that is confusing, this is a perfect opportunity to include
some comments in the code that will explain what is going on. Not only will this help you remember it later on, but
if you someone else views your code they will also be able to understand the code (hopefully)!
Another great thing about comments is the ability for comments to remove bits of code from execution when you
are debugging your scripts. This lesson will teach you how to create two types of comments in Javascript: single
line comments and multi-line comments.
117
Creating Single Line Comments
To create a single line comment in Javascript you place two slashes "//" in front of the code or text you wish to
have the Javascript interpreter ignore. When you place these two slashes, all text to the right will be ignored, until
the next line.
These types of comments are create for commenting out single lines of code and writing small notes.
118
<html>
<script type="text/javascript">
// This is a single line Javascript comment document.write("I have comments in my Javascript code!")
//document.write("You can't see this!"); </script>
<html>
119
I have comments in my Javascript
code!
120
Creating Multi-line Comments
Although a single line comment is quite useful, it can sometimes be burdensome to use for large
segments of code you wish to disable or extra long winded comments you need to insert. For this
large comments you can use Javascript's multi-line comment that begins with /* and ends with */.
121
<html>
<script type="text/javascript">
document.write("I have multi-line comments!");
/*document.write("You can't see this!"); document.write("You
can't see this!"); document.write("You can't see this!");
document.write("You can't see this!"); document.write("You can't
see this!"); document.write("You can't see this!");
document.write("You can't see this!");*/ </script>
</html>
122
I have multi-line comments!
Quite often text editors have the ability to comment out many lines of code with a simple key
stroke or option in the menu. If you are using a specialized text editor for programming be
sure that you check and see if it has an option to easily comment out many lines of code!
123
Javascript Array
An array is a variable that can store many variables. Many programmers
have seen arrays in other languages and they aren't that different in
Javascript
124
The following points should always be remembered when using arrays in Javascript:
The array is a special type of variable.
Values are stored into an array by using the array name and by stating the location in the array you wish to store the value in brackets.
Example:
myArray[2] = "Hello World";
Values in an array are accessed with the array name and location of the value.
Example:
myArray[2];
Javascript has built in functions for arrays, so check out these built in array functions before writing code yourself!
125
Creating a Javascript Array
Creating an array is slightly different than 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. This example shows how you would create a simple array, store values to it and
access these values.
126
<html>
<script type="text/javascript">
var myArray = new Array()
myArray[0] = "Baseball”
myArray[1] = "Cricket"
myArray[2] = "Football" document.write(myArray[0] + myArray[1] + myArray[2]);
</script></html>
127
128
Display:
FootballBaseballCricket
Notice that you set values and get values from an array by specifying the
position, in brackets, of the value you want to use.
129
Javascript Array Sorting
Imagine that you wanted to sort an array alphabetically before you wrote
the array to the browser. Well, this code has already been written and can
be accessed by using the Array'ssort method.
130
<html>
<script type="text/javascript">
var myArray = new Array()
myArray[0] = “q“
myArray[1] = “w“
myArray[2] = “e“
myArray.sort()
document.write(myArray[0] + myArray[1] + myArray[2]);
</script><html>
131
132
Javascript Alert - What is it?
If you do not have Javascript enabled on your web browser, then you may have been able to avoid
them in your internet history. The Javascript alert is a dialogue box that pops up and takes the
focus away from the current window and forces the web browser to read the message
133
You may have noticed that you didn't get a Javascript alert popup when you
came to this page. That is because doing so would be in bad taste for a web
designer. You see, alerts should be very, very rarely used and even then these
following guidelines should be considered when using them.
134
When to Use Popups / Alerts
Javascript alerts are ideal for the following situations:
If you want to be absolutely sure they see a message before doing anything on the website.
You would like to warn the user about something. For example "the following page contains humor not suitable for those under the age of 14."
An error has occurred and you want to inform the user of the problem.
When asking the user for confirmation of some action. For example they have just agreed to sign over the deed to their house and you want to ask them again if they are
absolutely positive they want to go through with this decision!
Even though the above situations would all be valid times to use the alert function, you could also skip the alert and just have the error message, confirmation, etc displayed in
plain HTML, instead of in a popup. More and more bigger sites are opting to lose the Javascript alerts and instead keep everything in HTML.
135
Coding a Simple Javascript Alert
Just for fun, let us suppose that we are making an alert for some website that asks people to hand
over the deed to their house. We need to add an alert to be sure these people are in agreement.
The following code will add an alert by using an HTML button and the onClick event.
136
<html>
<form>
<input type="button" onclick= "alert('Are you sure you want to give us the deed to your house?')" value="Confirmation
Alert">
</form>
</html>
137
138
139
Javascript Confirm
The Javascript confirm function is very similar to the Javascript alert function. A small dialogue box pops up and
appears in front of the web page currently in focus. The confirm box is different than the alert box in that it
supplies the user with a choice, they can either press OK to confirm the popups message or they can press cancel
and not agree to the popups request.
140
Confirmation are most often used to confirm an important action that is
taking place on a website. For example they may be about to submit an order
or about to visit a link that will take them away from the current website.
141
Javascript Confirm Example
142
<html> <head>
<script type="text/javascript">
function confirmation()
{
var answer = confirm(“hello atul")
if (answer)
{
alert("Bye bye!")
window.location = “tt.html“
}
else
{ alert("Thanks for sticking around!") } }
</script> </head>
<body> <form>
<input type="button" onclick="confirmation()" value="Leave atul.com"> </form> </body> </html>
143
144
145
146
147
148
149
Confirm returns the value 1 if the user clicks OK and the value 0 if the user clicks Cancel. We store this value in answer by setting it
equal to the confirm function call.
After answer has stored the value, we then use answer as a conditional statement. If answer is anything but zero, then we are going
to send the user away from tt.html . If answer is equal to zero, then we will keep the user at ttt.html because they clicked the
Cancel button.
In either case we have a Javascript alert box that appears to inform the user what is going to happen. "Bye bye!" if they chose to
leave and "Thanks for sticking around!" if they chose to stay
150
In this lesson we also used the window.location property for the first
time. Whatever we set window.location to will be where the browser
is redirected to.We will also discuss redirection later on.
151
Javascript Prompt
The Javascript prompt is a relic from the 1990's that you seldom see being used in
modern day websites. The point of the Javascript prompt is to gather information from
the user so that it can be used throughout the site to "personalize" it for the visitor.
152
Back in the day you'd often see these prompts on personal web pages asking for your name. After you
typed in the information you would be greeted with a page that had a welcome message, such as
"Welcome to My Personal Web Page ATUL Kahate!" (If you name just happened to be ATUL Kahate).
The Javascript prompt is not very useful and many find it slightly annoying, but hey, this lesson is
here to educate you, so let's learn how to make that prompt!
153
Simple Javascript Prompt
You can use a prompt for a wide variety of useless tasks, but below we use it for an
exceptionally silly task. Our prompt is used to gather the user's name to be displayed in our alert
dialogue box.
154
<html>
<head>
<script type="text/javascript">
function prompter() {
var reply = prompt("Hey there, good looking stranger! What's your name?", "")
alert (reply) } </script> </head>
<body>
<input type="button" onclick="prompter()" value="Say my name!"> </body>
155
156
157
158
Recap on Javascript Prompt
It sure is a quick way to gather some information, but it is not as a reliable information gatherer
as the other options available to you. If you want to find out someone's name and information, the
best way to request this information would be to use HTML Forms.
159
Javascript Print Function
The Javascript print function performs the same operation as the print option that you see at
the top of your browser window or in your browser's "File" menu. The Javascript print function
will send the contents of the webpage to the user's printer.
160
Many believe this function to be worthless, but there are many computer
users that do not know their way around a computer all that well and it can
sometimes create a more user friendly experience when you provide as many
helpful features as possible
161
Javascript Print Script - window.print()
The Javascript print function window.print() will print the current web page when
executed. In this example script we will be placing the function on a Javascript
button that will perform the print operation when the onClick event occurs.
162
HTML & Javascript Code:
<HTML>
<form> <input type="button" value="Print This Page" onClick="window.print()" /> </form>
</HTML>
163
164
165
JavaScript Redirect
You're moving to a new domain name. You have a time-delay in place on your download
site. You have a list of external web servers that are helping to mirror your site. What
will help you deal and/or take advantage of these situations? Javascript redirects will.
166
When a web page is moved will most probably would like to place a "redirect"
page at the old location that informs the visitor of the change and then after
a timed delay, will forward the visitor to the new location. With the
javascript redirection, you can do just this.
167
Javascript Window.Location
The control over what page is loaded into the browser rests in the javascript propety
window.location, by setting this equal to a new URL you will in turn change from the current
web page to the one that is specified. If you wanted to redirect all your visitors to
www.google.com when they arrived at your site you would just need the script below:
168
HTML & Javascript Code:
<script type="text/javascript"> window.location =
"http://www.google.com/" </script>
169
Javascript Time Delay
Implementing a timed delay in javascript is useful for the following situations:
Showing an "Update your bookmark" page when you have to change URLs or page locations
For download sites that wish to have a few second delay before the page loads and when the download starts
To refresh a web page every specified amount of seconds
The code for this timed delay is slightly involved and is beyond the scope of this tutorial. However, we have tested it and it seems to
function properly.
170
Redirect a web page
There are a couple of ways to redirect to another webpage with JavaScript. The
most popular ones are location.href and location.replace:
window.location.href = "http://www.w3schools.com";
The difference between href and replace, is that replace() removes the URL of
the current document from the document history, meaning that it is not
possible to use the "back" button to navigate back to the original document.
<html> <head>
<script type="text/javascript">
function delayer()
{ window.location = “tt.html" } </script> </head>
<body onLoad="setTimeout('delayer()', 5000)"> <h2 >Prepare to be redirected!</h2> <p>This page is a time delay
redirect, please update your bookmarks to our new location!</p> </body> </html>
172
173
174
The most important part of getting the delay to work is being sure to use the javascript function setTimeout. We
want the delayer() function be used after 5 seconds or 5000 miliseconds, so we pass the setTimeout() two arguments.
'delayer()' - The function we want setTimeout() to execute after the specified delay.
5000 - the number of milisecods we want setTimeout() to wait before executing our function. 1000 miliseconds = 1
second.
175
Web Page Redirection
Do use javascript for redirections when you change your website's URL or move a file to a new
location. Don't use redirections when they could easily be replaced with a normal HTML
hyperlink.
176
Javascript Popups
Chances are if you are reading this web page then you have experienced hundreds of Javascript
popup windows throughout your web surfing lifetime. Want to dish out some pain of your own
creation onto unsuspecting visitors? I hope not! Because web sites with irrelevant popups are
bad!
177
However, we will show you how to make windows popup for reasonable
occasions, like when you want to display extra information, or when you
want to have something open a new window that isn't an HTML anchor tag
<a>.
178
Javascript window.open Function
The window.open() function creates a new browser window, customized to
your specifications, without the use of an HTML anchor tag. In this example we
will be making a function that utilizes the window.open() function.
179
<head> <script type="text/javascript"> function myPopup()
{ window.open( “tt.html" ) }
</script> </head> <body> <form> <input type="button" onClick="myPopup()"
value="POP!"> </form> <p onClick="myPopup()">CLICK ME TOO!</p> </body>
180
181
182
This works with pretty much any tag that can be clicked
on, so please go ahead an experiment with this fun little
tool.
183
Javascript Window.Open Arguments
There are three arguments that the window.open function takes. First the relative or
absolute URL of the web page to be opened. Secondly, a text name for the window, and
lastly a long string that contains all the different properties of the window.
184
dependent - Subwindow closes if parent(the window that opened it) window closes
fullscreen - Display browser in full screen mode
height - The height of the new window, in pixels
width - The width of the new window, in pixels
left - Pixel offset from the left side of the screen
top - Pixel offset from the top of the screen
resizable - Allow the user to resize the window or prevent resizing
status - Display the status bar or not
185
Dependent, fullscreen, resizable, and status are all examples of ON/OFF
properties. You can either set them equal to zero to turn them off, or set
them to one to turn them ON. There is no inbetween setting for these types
of properties
186
Upgraded Javascript Popup Window!
Now that we have the tools, let's make a sophisticated
Javascript popup window that we can be proud of.
187
<head> <script type="text/javascript"> function myPopup2()
{ window.open( “tt.html", "myWindow", "status = 0, height = 300, width = 300, resizable =
0" ) } </script> </head> <body> <form> <input type="button" onClick="myPopup2()"
value="POP2!"> </form> <p onClick="myPopup2()">CLICK ME TOO!</p> </body>
188
189
190
<head> <script type="text/javascript"> function myPopup2()
{ window.open( “tt.html", "myWindow", "status = 1, height = 300, width = 300, resizable =
0" ) } </script> </head> <body> <form> <input type="button" onClick="myPopup2()"
value="POP2!"> </form> <p onClick="myPopup2()">CLICK ME TOO!</p> </body>
191
192
Now that is a prime example of a worthless popup! When you make your
own, try to have them relate to your content, like a small popup that has no
navigation that just gives the definition or explanation of a word, sentence,
or picture!
193
Javascript Date and Time Object
The Date object is useful when you want to display a date or use a timestamp in some sort of
calculation. In java you can either make a Date object by supplying the date of your choice, or
you can let Javascript create a Date object based on your visitor's system clock. It is usually best
to let Javascript simply use the system clock.
194
When creating a Date object based on the computer's (not web server's!)
internal clock, it is important to note that if someone's clock is off by a few
hours or they are in a different time zone, then the Date object will create a
different time than the one created with your own computer.
195
Javascript Date Today (Current)
To warm up our Javascript Date object skills, let's do something easy. If you do
not supply any arguments to the Date constructor (this makes the Date object)
then it will create a Date object based on the visitor's internal clock.
196
<html>
<h4>It is now
<script type="text/javascript">
var currentTime = new Date()
document.write(currentTime )
</script> </h4>
</html>
197
198
Nothing shows up! That's because we still don't know the
methods of the Date object that let us get the information
we need(i.e. Day, Month, Hour, etc).
199
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 the date we have to utilize some or all of the
following functions
200
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 (1-31)
getMonth() - Number of month (0-11)
getFullYear() - The four digit year (1970-
9999)
201
<html>
<h4>It is now <script type="text/javascript">
var currentTime = new Date()
var month = currentTime.getMonth()
var day = currentTime.getDate()
var year = currentTime.getFullYear() document.write(month + "/" + day + "/" + year) </script> </h4>
</html>
202
203
Javascript Current Time Clock
Now instead of displaying the date we will display the format you might
see on a typical digital clock HH:MM AM/PM (H = Hour, M = Minute).
204
<html>
<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>
</html>
205
206
We check to see if hours or minutes is less than 10, if it is then we need to
add a zero to the beginning of minutes. This is not necessary, but if it is 1:01
AM then our clock would output "1:1 AM", which doesn't look very nice at all!
207
Javascript Form Validation
There's nothing more troublesome than receiving orders, guestbook entries, or other form
submitted data that are incomplete in some way. You can avoid these headaches once and for
all with Javascript's amazing way to combat bad form data with a technique called "form
validation".
208
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:
209
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
210
Form Validation - Checking for Non-Empty
This has to be the most common type of
form validation. You want to be sure that
your visitors enter data into the HTML fields
you have "required" for a valid submission.
Below is the Javascript code to perform this
basic check to see if a given HTML input is
empty or not.
211
<html>
<head>
<script type='text/javascript'>
function check(form)
{
var valu=form.fname.value
if(valu==“”)
alert(“plz enter something”)
else
document.write(valu) }
</script>
</head>
<form>
Required Field: <input type='text' name=“fname">
<input type='button' onclick=check(this.form) value='Check Field' />
</form>
212
215
216
Javascript document.getElementById
217
<html>
<head><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></head>
<input type='text' id='myText' >
<input type='button' onclick='notEmpty()' value='Form Checker' />
</html>
218
219
220
221
Form Validation - Checking for Non-
Empty
222
<html><head>
<script type='text/javascript'>
function isEmpty(elem, helperMsg)
{ if(elem.value.length == 0)
{ alert(helperMsg);
return true; }
return false; }
</script></head>
<form> Required Field:
<input type='text' id='req1'/> <input type='button' onclick="isEmpty(document.getElementById('req1’), 'Please Enter a Value')" value='Check Field' /> </form>
223
224
225
226
<html><head>
<script type='text/javascript'>
function isEmpty(elem, helperMsg)
{ if(elem.value.length == 0)
{ alert(helperMsg);
elem.focus();
return true; }
return false; }
</script></head>
<form> Required Field:
<input type='text' id='req1'/> <input type='button' onclick="isEmpty(document.getElementById('req1’), 'Please Enter a Value')" value='Check Field' /> </form>
227
228
229
230
The function isEmpty will check to see that the
HTML input that we send it has something in it.
elem is a HTML text input that we send this
function. Javascriptstrings have built in
properties, one of which is the length property
which returns the length of the string. The chunk
of code elem.value will grab the string inside the
input and by adding on length elem.value.length
we can see how long the string is.
231
As long as elem.value.length isn't 0 then it's not empty and
we return true, otherwise we send an alert to the user with
a helperMsg to inform them of their error and return false
232
Form Validation - Checking for All
Numbers
233
Regular Expression(RegExp)
Character Meaning
/ backslash is an escape character in string literals.
Ex: /[a-z]\s/I : an expression that searches for any letter in the range A-Z
followed by a whitespace character
^ Matches beginning of input
Ex: , /^A/ does not match the 'A' in "an A", but does match the 'A' in "An
E".
$ Matches end of input. For example, /t$/ does not match the 't' in "eater",
but does match it in "eat".
* Matches the preceding expression 0 or more times. Equivalent to {0,}. For
example, /bo*/ matches 'boooo' in "A ghost booooed" and 'b' in "A bird
warbled" but nothing in "A goat grunted".
+ Matches the preceding expression 1 or more times. Equivalent to {1,}.
For example, /a+/ matches the 'a' in "candy" and all the a's in
"caaaaaaandy", but nothing in "cndy".
? Matches the preceding expression 0 or 1 time. Equivalent to {0,1}.
For example, /e?le?/ matches the 'el' in "angel" and the 'le' in "angle" and
(x) Matches 'x' and remembers the match, as the following example shows. The
parentheses are called capturing parentheses. The '(foo)' and '(bar)' in the
pattern /(foo) (bar) \1 \2/ match and remember the first two words in the string
"foo bar foo bar".
(?:x) Matches 'x' but does not remember the match.
(?<=y)x Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead.
x(?!y) Matches 'x' only if 'x' is not followed by 'y'. This is called a negated lookahead
(?<=y)x Matches x only if x is preceded by y. This is called a lookbehind.
x|y Matches 'x', or 'y' (if there is no match for 'x').
{n} Matches exactly n occurrences of the preceding expression. N must be a positive
integer.
{n,} Matches at least n occurrences of the preceding expression. N must be a positive
integer.
{n,m} Where n and m are positive integers and n <= m. Matches at least n and at most m
occurrences of the preceding expression. When m is omitted, it's treated as ∞.
[xyz] Character set. This pattern type matches any one of the characters in the brackets,
including escape sequences.
[^xyz] A negated or complemented character set. That is, it matches anything that is not
enclosed in the brackets.
Sr.No Expression & Description
.
1 [...]
Any one character between the brackets.
2 [^...]
Any one character not between the brackets.
3 [0-9]
It matches any decimal digit from 0 through 9.
4 [a-z]
It matches any character from lowercase a through
lowercase z.
5 [A-Z]
It matches any character from uppercase A through
uppercase Z.
6 [a-Z]
<html><head>
<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></head>
<form> Numbers Only:
<input type='text' id='numbers'/> <input type='button' onclick="isNumeric(document.getElementById('numbers'), 'Numbers Only Please')" value='Check
Field' /> </form></html>
237
238
Form Validation - Checking
for All Letters
239
<html><head>
<script type='text/javascript'>
function isAlphabet(elem, helperMsg)
{ var alphaExp = /^[a-zA-Z]+$/;
if(elem.value.match(alphaExp))
{ return true; }
else{ alert(helperMsg);
elem.focus();
return false; } }
</script><head>
<form> Letters Only: <input type='text' id='letters'/> <input
type='button'
onclick="isAlphabet(document.getElementById('letters'),
'Letters Only Please')" value='Check Field' /> </form>
</html>
240
241
Form Validation - Checking for Numbers and Letters
242
<html><head>
<script type='text/javascript'>
function isAlphabet(elem, helperMsg)
{ var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp))
{ return true; }
else{ alert(helperMsg);
elem.focus();
return false; } }
</script><head>
<form> Letters Only: <input type='text' id='letters'/> <input
type='button'
onclick="isAlphabet(document.getElementById('letters'),
'Letters Only Please')" value='Check Field' /> </form>
</html>
243
244
Form Validation - Restricting the Length
245
<html<<head>
<script type='text/javascript'> 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; } }
</script></head>
<form> Username(6-8 characters):
<input type='text' id='restrict'/> <input type='button'
onclick="lengthRestriction(document.getElementById('restrict'), 6, 8)"
value='Check Field' /> </form> </html>
246
247
248
249
Form Validation - Selection Made
250
Form Validation - Selection Made
To be sure that someone has actually selected a choice from an HTML select input you can use a simple trick of
making the first option as helpful prompt to the user and a red flag to you for your validation code.
By making the first option of your select input something like "Please Choose" you can spur the user to both make a
selection and allow you to check to see if the default option "Please Choose" is still selected when the submit the
form.
251
function madeSelection(elem, helperMsg)
{
if(elem.value == "Please Choose")
{
alert(helperMsg);
elem.focus();
return false;
}
else
{
return true;
}}
252
<html><head>
<script type='text/javascript'>
function madeSelection(elem, helperMsg)
{ if(elem.value == "Please Choose")
{ alert(helperMsg);
elem.focus();
return false; }
else{ return true; } }
</script><head>
<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>
253
</html>
For e-mail
254
<script type='text/javascript'>
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>
Email: <input type='text' id='emailer'/> <input
type='button'
onclick="emailValidator1(document.getElementB
yId('emailer'), 'Not a Valid Email')" value='Check
Field' /> </form>
255
<html>
<head>
<script>
function validateForm() {
var x = document.forms["myForm"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert("Not a valid e-mail address");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm();" method="post">
Email: <input type="text" name="email">
<input type="submit" value="Submit">
</form>
</body>
</html>
Event Object
257
<html>
<head>
<script type="text/javascript">
function show_coords(event)
{
x=event.clientX
y=event.clientY
alert("X coords: " + x + ", Y coords: " + y)
}</script></head>
<body onmousedown="show_coords(event)">
<p>Click in the document. An alert box will alert the x and y coordinates of the
mouse pointer.</p></body></html>
258
259
<html>
<head>
<script type="text/javascript">
function whichButton(event)
{
alert(event.keyCode)
}
</script></head>
<body onkeyup="whichButton(event)">
<p><b>Note:</b> Make sure the right frame has focus when trying this example!</p>
<p>Press a key on your keyboard. An alert box will alert the unicode of the key pressed.</p>
</body>
</html>
260
261
<html>
<head>
<script type="text/javascript">
function isKeyPressed(event)
{
if (event.shiftKey==1)
{
alert("The shift key was pressed!")}
else
{ alert("The shift key was NOT pressed!")
}}</script></head>
<body onmousedown="isKeyPressed(event)">
<p>Click somewhere in the document. An alert box will tell you if you pressed the shift key or not.</p>
</body></html>
262
263
<html><head>
<script type="text/javascript">
function getEventType(event)
{
alert(event.type);
}
</script></head>
<body onmousedown="getEventType(event)">
<p>Click in the document.
An alert box will tell what type of event
that was triggered.</p>
</body>
</html>
264
265
DO IT
266
Directly Executing Javascript
in a Browser
267
<html>
<a href="javascript: alert('News Flash!')">News Flash</a>
</html>
268
269
Simple Javscript Void 0 Simple
Example
270
<html>
<a href="javascript: void(0)">I am a useless link</a>
</html>
271
272
Simple Javscript Void 0 Useful
Example
273
<html>
<a href="javascript: void(myNum=10);alert('myNum = '+myNum)">
Set myNum Please</a>
</html>
274
275
OBJECT IN JAVASCRIPT
276
Window
Frame
History
Location
document
form
text
Built-in Objects
Array
Date
String
277
String object
length()
278
<html>
<body>
<script type="text/javascript">
var txt="Hello World!"
document.write(txt.length)
</script>
</body>
</html>
279
12
280
<html><body><script type="text/javascript">
var txt="Hello World!"
document.write("<p>Big: " + txt.big() + "</p>")
document.write("<p>Small: " + txt.small() + "</p>")
document.write("<p>Bold: " + txt.bold() + "</p>")
document.write("<p>Italic: " + txt.italics() + "</p>")
document.write("<p>Blink: " + txt.blink() + " (does not work in IE)</p>")
document.write("<p>Fixed: " + txt.fixed() + "</p>")
document.write("<p>Strike: " + txt.strike() + "</p>")
document.write("<p>Fontcolor: " + txt.fontcolor("Red") + "</p>")
document.write("<p>Fontsize: " + txt.fontsize(16) + "</p>")
document.write("<p>Lowercase: " + txt.toLowerCase() + "</p>")
document.write("<p>Uppercase: " + txt.toUpperCase() + "</p>")
document.write("<p>Subscript: " + txt.sub() + "</p>")
document.write("<p>Superscript: " + txt.sup() + "</p>")
document.write("<p>Link: " + txt.link("http://www.w3schools.com") + "</p>")
</script></body></html>
281
282
indexOf()
283
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
284
285
replace()
286
<html>
<body>
<script type="text/javascript">
var str="Visit Microsoft!"
document.write(str.replace(/Microsoft/,“IMS"))
</script>
</body>
</html>
287
288
Math object
289
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
290
291
<html>
<body>
<script type="text/javascript">
document.write(Math.random())
</script>
</body>
</html>
292
293
<html>
<body>
<script type="text/javascript">
document.write(Math.max(5,7) + "<br />")
document.write(Math.max(-3,5) + "<br />")
document.write(Math.max(-3,-5) + "<br />")
document.write(Math.max(7.25,7.30))
</script></body>
</html>
294
295
<html>
<body>
<script type="text/javascript">
document.write(Math.min(5,7) + "<br />")
document.write(Math.min(-3,5) + "<br />")
document.write(Math.min(-3,-5) + "<br />")
document.write(Math.min(7.25,7.30))
</script></body>
</html>
296
297
<html>
<body>
<script type="text/javascript">
</script>
</body>
</html>
298
299
Window object
300
<html>
<body>
<script type="text/javascript">
myWindow=window.open('','','width=200,height=100')
myWindow.document.write("This is 'myWindow'")
myWindow.focus()
</script>
</body>
</html>
301
302
<html>
<head>
<script type="text/javascript">
function closeWin()
{ myWindow.close()}
</script></head><body>
<script type="text/javascript">
myWindow=window.open('','','width=200,height=100')
myWindow.document.write("This is 'myWindow'")
</script>
<input type="button" value="Close 'myWindow'" onclick="closeWin()" />
</body>
</html>
303
304
<html> <head>
<script type="text/javascript">
function goBack() { window.history.back()
}
</script> </head>
<body><input type="button" value="Back" onclick="goBack()" /></body> </html>
305
306
The go() method loads a specific page in the history list.
Syntax
history.go(number|URL)
307
<html> <head>
<script type="text/javascript">
function goBack()
{
window.history.go(-1)
} </script> </head>
<body>
<input type="button" value="Back" onclick="goBack()" >
</body> </html>
308
Examples
309
<HTML>
<HEAD>
<TITLE>JavaScript Example</TITLE>
</HEAD><BODY>
<CENTER>
<FORM><INPUT TYPE="button" VALUE="silver"
ONCLICK="document.bgColor='silver'">
<INPUT TYPE="button" VALUE="slate"
ONCLICK="document.bgColor='lightslategray'">
<INPUT TYPE="button" VALUE="green"
ONCLICK="document.bgColor='lightgreen'">
<INPUT TYPE="button" VALUE="blue"
ONCLICK="document.bgColor='lightblue'">
<INPUT TYPE="button" VALUE="white"
ONCLICK="document.bgColor='white'">
</FORM></BODY></HTML>
310
311
312
313
Example 2
314
<html><head>
<script type="text/javascript" language="JavaScript">
function handler(c){
c.checked = true;
return 0 }
</script></head>
<form name="formA" action="javascript:void(0)">
<textarea rows="10" cols="45" onclick="handler(formA.click)" onmouseover="handler(formA.over)"></textarea>
<br><br>
Click<input type="checkbox" name="click">
MouseOver<input type="checkbox" name="over">
</form></html>
315
316
Example 3
317
<html><head>
<script type="text/javascript" language="JavaScript">
function handler(c,t,s) {
t.value=s
c.checked = true;
return 0 }</script></head>
<form name="formA" action="javascript:void(0)">
<textarea rows="10" cols="45" onclick="handler(formA.click,formB.t1,'click')" onmouseover="handler(formA.over,formB.t1,'mouseover')"></textarea><br><br>
Click<input type="checkbox" name="click">
MouseOver<input type="checkbox" name="over">
</form>
<form name="formB">
<textarea name="t1" rows="8" cols="45" wrap='soft'></textarea>
</html>
318
319
Example 4
320
<htrml><head>
<script type="text/javascript" language="JavaScript">
function handler(t,c,s)
{
t.value += s;
c.checked = true;
return 0
}
</script>
</head>
321
ondblclick= "handler(formB.t1, formB.dblclick, 'dblclick ')"
onmouseover="handler(formB.t1, formB.over, 'over ')"
onmouseout= "handler(formB.t1, formB.out, 'out ')" >
Move the mouse, click and type here. Try selecting text.
</textarea>
<input type="Reset"> <input type="Submit" value="Submit">
</form>
<form name="formB">
<textarea name="t1" rows="8" cols="45" wrap="soft"></textarea>
click:<input type="checkbox" name="click">
</form>
322
323
Example 5
324
<html><head>
<script type="text/javascript">
txtsize=0
maxsize=100
function writemsg()
{if (txtsize<maxsize) {
document.getElementById('msg').style.fontSize=txtsize
txtsize++
timer=setTimeout("writemsg()",10) }}
function stoptimer()
{clearTimeout(timer)}
</script></head>
<body onload="writemsg()" onunload="stoptimer()">
<p id="msg">Hello Everyone!</p>
</body></html>
325
326
Example 6
327
<html><head><script type="text/javascript">
function newColor(color)
{document.getElementById('x').style.background=color}
</script></head><body>
<p>This example demonstrates how to change
the background color of a textarea.</p>
<p>Mouse over the three colored table cells,
and the textarea will change color:</p>
<table width="100%"><tr>
<td bgcolor="red"
onmouseover="newColor('red')"> </td>
<td bgcolor="blue"
onmouseover="newColor('blue')"> </td>
<td bgcolor="green"
onmouseover="newColor('green')"> </td>
</tr></table>
<form>
<textarea id="x" rows="5" cols="20">
</textarea>
</form></body></html>
328
329
<html><head>
<script language=javascript type="text/javascript">
x = "This text will scroll to the left slowly! ... "
x=x+x
i=0
function scroll(){
window.defaultStatus=x.substring(i,x.length) + x
i++
if (i==x.length)
i=0 ;
tid=setTimeout("scroll()", 100)
}
y=" "
function stopScroll(){
window.defaultStatus=" "
window.clearTimeout(tid);
} </script></head>
<body onLoad="scroll()" onUnload="stopScroll()">
</body></html>
330
331
<html><head><script language=javascript type="text/javascript">
var plus,minus,divide,times
function initialise(){
plus=document.calc.operator.options[0]
minus=document.calc.operator.options[1]
divide=document.calc.operator.options[2]
times=document.calc.operator.options[3]}
function calculate(){
x = parseInt(document.calc.val1.value)
y = parseInt(document.calc.val2.value)
if (plus.selected)
document.calc.answer.value=x + y
if (minus.selected)
document.calc.answer.value=x - y
if (divide.selected)
document.calc.answer.value=x / y
if (times.selected)
document.calc.answer.value=x * y}</script></head>
332
<body onLoad="initialise()">
<h2>Calculator</h2>
<form name="calc" action="post">
<input type=text name=val1 size=10>
<select name=operator><option value=plus>+
<option value=minus>-<option value=divide>/
<option value=times>*</select>
<input type=text name=val2 size=10>=
<input type=text name=answer size=10>
<input type=button value=answer onClick="calculate()">
</form</body></html>
333
334
Changing Text with innerHTML
335
<html><head>
<script type="text/javascript">
function changeText()
{ document.getElementById('boldStuff').innerHTML = ‘ATUL KAHATE'; }
</script></head> <body>
<form>
<p>Welcome to the site <b id='boldStuff'>dude</b> </p> <input type='button' onclick='changeText()' value='Change Text'/>
</form> </body> </html>
336
337
338
Updating Text Based on User Input
339
<script type="text/javascript">
function changeText2()
{
var userInput = document.getElementById('userInput').value;
340
341
342
<html>
<head>
<script type="text/javascript">cc=0
function changeimage()
{If (cc==0)
{cc=1
document.getElementById('myimage').src="bulbon.gif"
}else
{cc=0
document.getElementById('myimage').src="bulboff.gif"
}}</script></head><body>
<img id="myimage" onclick="changeimage()"
border="0" src="bulboff.gif"
width="100" height="180" />
<p>Click to turn on/off the light</p></body>
</html>
343
344
345
DHTML WITH JAVASCRIPT
346
DHTML is NOT a W3C Standard
DHTML stands for Dynamic HTML.
DHTML is not a standard defined by the World Wide Web Consortium (W3C). DHTML is a "marketing term" - used by Netscape and Microsoft to describe
the new technologies the 4.x generation browsers would support.
DHTML is a combination of technologies used to create dynamic Web sites.
To most people DHTML means a combination of HTML 4.0, Style Sheets and JavaScript.
W3C once said: "Dynamic HTML is a term used by some vendors to describe the combination of HTML, style sheets and scripts that allows documents to
be animated."
347
DHTML CSS Positioning
348
<html><head><style>
h1.ex1{
position:relative;
left:20px;}
h1.ex2{
position:relative;
left:-20px;}
</style></head><body>
<h1>Normal Heading</h1>
<h1 class="ex1">Heading +20</h1>
<h1 class="ex2">Heading -20</h1>
<p>
Relative positioning moves an element relative to its original position.
</p><p>
"left:20" adds 20 pixels to the element's LEFT position.
</p><p>
"left:-20" subtracts 20 pixels from the element's LEFT position.
</p></body>
</html>
349
350
<html><head><style>
h1.x{
position:absolute;
left:100px;
top:150px;
}</style></head><body>
<h1 class="x">This is a heading</h1>
<p>With absolute positioning, an element can be placed anywhere on a page.</p>
<p>The LEFT position of the heading is 100 pixels from the left of the page.
The TOP position is 150 pixels from the top of the page.</p>
</body></html>
351
352
DHTML Document Object Model
353
<html>
<body>
<h1 id="header">My header</h1>
<script type="text/javascript">
document.getElementById('header').style.color="red"
</script>
<p><b>Note:</b> It is the script that changes the style of the element!</p>
</body></html>
354
355
DHTML Event Handlers
356
<html>
<body>
<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">
Mouse over this text</h1>
</body>
</html>
357
358
<html><body>
<p>Move the mouse over the words to see the cursor change</p>
<span style="cursor: auto">Auto</span><br />
<span style="cursor: crosshair">Crosshair</span><br />
<span style="cursor: default">Default</span><br />
<span style="cursor: pointer">Pointer</span><br />
<span style="cursor: hand">Hand</span><br />
<span style="cursor: move">Move</span><br />
<span style="cursor: e-resize">e-resize</span><br />
<span style="cursor: ne-resize">ne-resize</span><br />
<span style="cursor: nw-resize">nw-resize</span><br />
<span style="cursor: n-resize">n-resize</span><br />
<span style="cursor: se-resize">se-resize</span><br />
<span style="cursor: sw-resize">sw-resize</span><br />
<span style="cursor: s-resize">s-resize</span><br />
<span style="cursor: w-resize">w-resize</span><br />
<span style="cursor: text">text</span><br />
<span style="cursor: wait">wait</span><br />
<span style="cursor: help">help</span><br />
</body></html>
359
360
<html>
<body>
<h1 onmouseover="style.color='red'"
onmouseout="style.color='black'">
Mouse over this text</h1>
</body>
</html>
361
362
<html><head><script type="text/javascript">
function blinking_header()
{
if (!document.getElementById('blink').style.color)
{document.getElementById('blink').style.color="red" }
if (document.getElementById('blink').style.color=="red")
{document.getElementById('blink').style.color="black"}
else{document.getElementById('blink').style.color="red"}
timer=setTimeout("blinking_header()",100)}
function stoptimer(){clearTimeout(timer)}
</script></head>
<body onload="blinking_header()" onunload="stoptimer()">
<h1 id="blink">Blinking header</h1>
</body></html>
363
364
<html><head><script type="text/javascript">
function moveleft()
{document.getElementById('image').style.position="absolute"
document.getElementById('image').style.left="0"}
function moveback()
{document.getElementById('image').style.position="relative"}
</script></head>
<body><img id="image" src="bulbon.gif"
onmouseover="moveleft()"
onmouseout="moveback()"
width="100" height="180" /></body></html>
365
366
<html><head><script>
function startEQ()
{richter=5
parent.moveBy(0,richter)
parent.moveBy(0,-richter)
parent.moveBy(richter,0)
parent.moveBy(-richter,0)
timer=setTimeout("startEQ()",10)}
function stopEQ()
{clearTimeout(timer)}
</script></head><body><form>
<input type="button" onclick="startEQ()" value="Start an earthquake"><br /><br />
<input type="button" onclick="stopEQ()" value="Stop the earthquake"></form></body></html>
367
368
<html><head>
<script type="text/javascript">
var i=0
txt=new Array("trailA","trailB","trailC")
function cursor(interval){
pos=i*8+5
if (interval=='first'){i=0}
if (i==0){
xpos=event.clientX
ypos=event.clientY
document.all(txt[i]).style.visibility="visible"
document.all(txt[i]).style.position="absolute"
document.all(txt[i]).style.left=xpos+5
document.all(txt[i]).style.top=ypos+5 }
else{
document.all(txt[i]).style.visibility="visible"
document.all(txt[i]).style.position="absolute"
document.all(txt[i]).style.left=xpos+pos
document.all(txt[i]).style.top=ypos+pos}
if (i==txt.length){i=i}
else{i++}
setTimeout("cursor('next')",10)}
</script></head><body onmousemove="cursor('first')">
<h1>Move the cursor over this page</h1>
<span id="trailA" style="visibility:hidden">W</span>
<span id="trailB" style="visibility:hidden">3</span>
<span id="trailC" style="visibility:hidden">S</span>
</body>
</html>
369
370
<html><head><script type="text/javascript">
var c=0
var t
function timedCount()
{
document.getElementById('txt').value=c
c=c+1
t=setTimeout("timedCount()",1000)
}
function stopCount()
{
clearTimeout(t)
}
</script></head><body><form>
<input type="button" value="Start count!" onClick="timedCount()">
<input type="text" id="txt">
<input type="button" value="Stop count!" onClick="stopCount()">
</form>
</body>
</html>
371