JavaScript Final Notes Updated
JavaScript Final Notes Updated
JavaScript was first known as LiveScript, but Netscape changed its name to JavaScript, possibly because
of the excitement being generated by Java. JavaScript made its first appearance in Netscape 2.0 in 1995
with the name LiveScript. The general-purpose core of the language has been embedded in Netscape,
Internet Explorer, and other web browsers.
Javascript can be thought of as an extension to HTML which allows authors to incorporate some
functionality in their web pages. So now, whenever the user presses the SUBMIT button, you
don't necessarily have to invoke a Common Gateway Interface (cgi) script to do the processing.
If it is something simple, you can do the processing locally using Javascript and give back the
results. Javascript can also be used in a number of ways to spice up your page.
JavaScript:
• was designed to add interactivity to HTML pages
• is a scripting language.
• is a lightweight programming language.
• is usually embedded directly into HTML pages.
• is an interpreted language (means that scripts execute without preliminary compilation).
• can be used by everyone without purchasing a license.
Limitations of JavaScript
• We cannot treat JavaScript as a full-fledged programming language. It lacks the
following important features:
• Client-side JavaScript does not allow the reading or writing of files. This has been kept
for security reason.
• JavaScript cannot be used for networking applications because there is no such support
available.
• JavaScript doesn't have any multithreading or multiprocessor capabilities.
JavaScript Syntax
JavaScript can be implemented using JavaScript statements that are placed within the <script>...
</script> HTML tags in a web page.
You can place the <script> tags, containing your JavaScript, anywhere within you web page, but it is
normally recommended that you should keep it within the <head> tags.
The <script> tag alerts the browser program to start interpreting all the text between these tags as a script.
A simple syntax of your JavaScript will appear as follows.
<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.
• Type: This attribute is what is now recommended to indicate the scripting language in use and its
value should be set to "text/javascript".
Syntax Rules
• Statements may contain a semicolon at the end of them as in C, but it is not necessary
unless there are multiple statements on one line. Multiple statements on one line must be
separated by a semicolon.
• JavaScript is case sensitive.
• Quotes may be single quote (') or double quote ("). When embedded within each other
they must be used consistently as in the following example.
• Comments are the same as in C++ with the "//" characters for a single line comment, and
the "/*" for the beginning of a multiline comment and the "*/" for the end of a multiline
comment.
• Variables must be defined before they are used.
JavaScript Code
Let us take a sample example to print out "Hello World". We added an optional HTML comment
that surrounds our JavaScript code. This is to save our code from a browser that does not support
JavaScript. The comment ends with a "//-->". Here "//" signifies a comment in JavaScript, so we
add that to prevent a browser from reading the end of the HTML comment as a piece of
JavaScript code. Next, we call a function document.write which writes a string into our HTML
document.
This function can be used to write text, HTML, or both. Take a look at the following code.
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
document.write ("Welcome to JavaScript!")
//-->
</script>
</body>
</html>
Welcome to 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.
• The HTML comment closing sequence --> is not recognized by JavaScript so it should
be written as //-->.
JavaScript Placement
There is a flexibility given to include JavaScript code anywhere in an HTML document.
However the most preferred ways to include JavaScript in an HTML file are as follows:
• Script in <head>...</head> section.
In the following section, we will see how we can place JavaScript in an HTML file in different
ways.
1. JavaScript in <head>...</head> Section
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 as follows.
<html>
<head>
<script type="text/javascript">
<!--
function sayHello() {
alert("Hello World")
}
//-->
</script>
</head>
<body>
Click here for the result
</body>
</html>
This code will produce the following results:
Hello World
Say Hello
Hello World
Say Hello
For example, you can keep the following content in filename.js file and then you can use
sayHello function in your HTML file after including the filename.js file.
function sayHello() {
alert("Hello World")
}
JavaScript Variables
Local Variables: A local variable will be visible only within a function where it is
defined. Function parameters are always local to that function.
Within the body of a function, a local variable takes precedence over a global
variable with the same name. If you declare a local variable or function parameter
with the same name as a global variable, you effectively hide the global variable.
Take a look into the following example.
<script type="text/javascript">
<!--
var myVar = "global"; // Declare a global variable
function checkscope( ) {
var myVar = "local"; // Declare a local variable
document.write(myVar);
}
//-->
</script>
It will produce the following result:
Local
DataTypes
• Numbers - are values that can be processed and calculated. You don't enclose them in
quotation marks. The numbers can be either positive or negative.
• Strings - are a series of letters and numbers enclosed in quotation marks. JavaScript uses
the string literally; it doesn't process it. You'll use strings for text you want displayed or
values you want passed along.
• Boolean (true/false) - lets you evaluate whether a condition meets or does not meet
specified criteria.
• Null - is an empty value. null is not the same as 0 -- 0 is a real, calculable number,
whereas null is the absence of any value.
Arithmetic Operators
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
–– Decrement
- Negation
Bitwise Operators
These operators work at the bit level performing the operator function on a bit per bit basis. The
operation must be thought of as binary, octal, or hexadecimal values (depending on preference)
to consider how it works. Consider the decimal number 15.
Logical Operators
Logical operators operate on boolean values which are either true or false.
Operator Meaning
&& AND
|| OR
! NOT
? Conditional
, Comma
if
if (value == 3)
{
document.write("Value is three")
}
else
{
document.write("Value is not three")
}
While
var i = 0
while (i < 3)
{
i++
}
Do While
days = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
var day = 0
do
{
document.write(days[day] + " is day " + eval(day+1) + " of the
week.<BR>\n")
day++
} while (day < 7)
For
The following example will determine what numeric day of the week Wednesday falls on.
days = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturda
y")
var day = "Wednesday"
var place
for (i = 0;i < days.length;i++)
{
if (day == days[i])
{
place = i + 1
}
}
document.write(day + " is day " + place + " in the week.<BR>\n")
Runs one or more commands based on the value of the expression being evaluated. An
example is:
switch (day) {
case 1:
document.write("Sunday<BR>\n")
break
case 2:
document.write("Monday<BR>\n")
break
case 3:
document.write("Tuesday<BR>\n")
break
case 4:
document.write("Wednesday<BR>\n")
break
case 5:
document.write("Thursday<BR>\n")
break
case 6:
document.write("Friday<BR>\n")
break
case 7:
document.write("Saturday<BR>\n")
break
default:
document.write("Invalid Weekday<BR>\n")
break
}
Break
The break statement may be used to break out of a while, if, switch, dowhile, or for
statement. The break causes program control to fall to the statement following the iterative
statement. The break statement now supports a label which allows the specification of a
location for the program control to jump to. The following code will print "Wednesday is day
4 in the week".
days = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturda
y")
var day = "Wednesday"
var place
for (i = 0;i < days.length;i++)
{
if (day == days[i]) break;
}
place = i + 1
document.write(day + " is day " + place + " in the week.<BR>\n")
Continue
The continue statement does not terminate the loop statement, but allows statements below
the continue statement to be skipped, while the control remains with the looping statement.
The loop is not exited. The example below does not include any ratings values below 5.
For in Statement
Executes a loop similar to a for statement that executes for all the properties in an object. The
example below lists all properties and their values for the document object. The document is
the HTML page being displayed.
for (i in document)
{
document.write("Property = " + i + " Value = " + document[i] +
"<BR>\n")
}
With Statement
Eliminates references to the object within the statement by identifying the default object to be
used inside the braces. This example prints out the document properties and values without
referencing the document object to perform the function.
with (document)
{
for (i in this)
{
write("Property = " + i + " Value = " + document[i] + "<BR>\n")
}
}
Defining Functions
Javascript functions are defined using the key word "function" followed by its name and
variables being passed to it in the following syntax:
An example:
<HTML>
<HEAD>
<TITLE>A function definition</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- Hiding JavaScript
function listItems(itemList)
{
document.write("<UL>\n")
for (i = 0;i < itemList.length;i++)
{
document.write("<LI>" + itemList[i] + "\n")
}
document.write("</UL>\n")
}
// End hiding JavaScript -->
</SCRIPT>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
days = new
Array("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday")
listItems(days)
// -->
</SCRIPT>
</BODY>
</HTML>
Calling Functions
If evaluate() is a defined function, the following line will call the function:
<SCRIPT LANGUAGE="JavaScript">
<!--
i3 = evaluate (Tree)
// -->
</SCRIPT>
This function may evaluate the members of the array tree to see how many match a certain
criteria.
Another way to call a function is to tie it to an anchor:
<A HREF="javascript:redirectLink()">redirecting</A>
This will cause the redirectLink() function to run when the text "redirecting" is clicked on. The
text inside the anchor reference is not marked as a link, nor does the mouse change when placed
over the text. This is one way to make truly invisible links, that no one would know had any
function until they click on it.
Functions Properties
Functions in JavaScript is actually an object. Therefore any created function created using the
"function" declaration will have the properties of a function. These properties are:
• arguments - An array of arguments passed to the function. This is an array object which
has a property of length which enables the programmer to tell how many arguments (or
variables)are passed to the function.
• caller - The name of the function that called the function.
• prototype - Used to make more properties.
The arguments array is a member of every function. It can be used to determine how many
variables are being passed to the function, and what they are, without each argument being
explicitly declared in the function. The following example performs the same task as the above
example:
function listItems()
{
var items = listItems.arguments.length
document.write("<UL>\n")
for (i = 0;i < items;i++)
{
document.write("<LI>" + listItems.arguments[i] + "\n")
}
document.write("</UL>\n")
}
listItems("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturd
ay","Happyday")
Local variables
Local variables may be defined inside functions. The following example uses the variables, sum
and items as local variables.
function average()
{
var items = average.arguments.length
var sum = 0
for (i = 0; i < items;i++)
{
sum += average.arguments[i]
}
return (sum/items)
}
document.write(average(6,9,8,4,5,7,8,10))
Return
As in the example above, the return statement will return a value to the statement that invoked
the function. In the above example, the average value is written to the document. The return
statement will return the value as float, string, integer or whatever is appropriate for use.
• escape(string) - Encodes a string from ASCII into an ISO Latin-1 (ISO 8859-1) character
set which is suitable for HTML processing. It is passed the string to be encoded, and
returns the encoded string.
• unescape - Converts an ISO8859-1 character set to ASCII.
• eval()- Converts a string to integer or float value. It can also evaluate expressions
included with a string. In the example, value1 becomes 62.
value1 = eval("124/2") ,
• isNaN(value) - If the value passed is a not a number, the boolean value of true is
returned, if it is a number, it returns false.
if (isNaN(string1))
{
document.write("String1 is not a number\n");
}
else
{
document.write(String1 is a number\n");
}
• parseFloat() - Returns floating point numbers the same as the parseInt function, but looks
for floating point qualified strings and returns their value as a float. The first line below
returns a value of 123, and the second line returns 9.683.
value1 = parseFloat("123")
value2 = parseFloat("9.683")
• parseInt()- Converts a string to an integer returning the first integer encountered which is
contained in the string. In the example, value1 becomes 12.
value1 = parseInt("12b13") ,
If no integer value were found such as in the string "abcd", then a value of 0 is returned.
• typeof operator - This is an operator but its usefullness is similar to a function. This
operator returns the type of the object it operates on. Values returned are string values
and may be one of "undefined", "object", "function", "number", "Boolean", or "string".
The example will return the string "number".
typeof 10
• taint
• untaint(element) -
valueOf()
• toString() - Converts an object to a string. The syntax is shown below. Radix is the base
value for the conversion, which may be 10 for decimal conversion. The value 1 is used
for binary conversion, and 8 is used for octal conversion.
object.tostring(radix)
Dialog Boxes
• alert(message) - Displays an alert box with a message defined by the string message.
Example:
• prompt(message) - Displays a box with the message passed to the function displayed. The
user can then enter text in the prompt field, and choose OK or Cancel. If the user chooses
Cancel, a NULL value is returned. If the user chooses OK, the string value entered in the
field is returned. An example:
JavaScript Events
JavaScript Events are items that transpire based on an action. A document event is the loading of
an HTML document. A form event is the clicking on a button. Events are objects with properties.
Event Properties
JavaScript defines five types of events which are form, image, image map, link, and window
events. Events are associated with HTML tags. The definitions of the events described below are
as follows:
Form Events
Link Events
Window Events
Event Association
Events are associated with HTML tags. The definitions of the events described below are as
follows:
• <A>
o click (onClick)
o mouseOver (onMouseOver)
o mouseOut (onMouseOut)
• <AREA>
omouseOver (onMouseOver)
omouseOut (onMouseOut)
• <BODY>
o blur (onBlur)
o error (onError)
o focus (onFocus)
o load (onLoad)
o unload (onUnload)
• <FORM>
o submit (onSubmit)
o reset (onReset
• <FRAME>
o blur (onBlur)
o focus (onFocus)
• <FRAMESET>
o blur (onBlur)
o error (onError)
o focus (onFocus)
o load (onLoad)
o unload (onUnload)
• <IMG>
o abort (onAbort)
o error (onError)
o load (onLoad)
• <INPUT TYPE = "button">
o click (onClick)
• <INPUT TYPE = "checkbox">
o click (onClick)
• <INPUT TYPE = "reset">
o click (onClick)
• <INPUT TYPE = "submit">
o click (onClick)
• <INPUT TYPE = "text">
o blur (onBlur)
o focus (onFocus)
o change (onChange)
o select (onSelect)
• <SELECT>
o blur (onBlur)
o focus (onFocus)
o change (onChange)
• <TEXTAREA>
o blur (onBlur)
o focus (onFocus)
o change (onChange)
o select (onSelect)
Event Handlers
As you can see, the event handling attribute is included in the HTML tag. When multiple
statements are included in the event handling code, the statements are separated by a semicolon.
<HTML>
<HEAD>
<TITLE>Using functions as event handlers</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function nameDefined(ckie,nme)
{
var splitValues
var i
for (i=0;i<ckie.length;++i)
{
splitValues=ckie[i].split("=")
if (splitValues[0]==nme) return true
}
return false
}
function delBlanks(strng)
{
var result=""
var i
var chrn
for (i=0;i<strng.length;++i) {
chrn=strng.charAt(i)
if (chrn!=" ") result += chrn
}
return result
}
function getCookieValue(ckie,nme)
{
var splitValues
var i
for(i=0;i<ckie.length;++i) {
splitValues=ckie[i].split("=")
if(splitValues[0]==nme) return splitValues[1]
}
return ""
}
function testCookie(cname, cvalue) { //Tests to see if the cookie
var cookie=document.cookie //with the name and value
var chkdCookie=delBlanks(cookie) //are on the client computer
var nvpair=chkdCookie.split(";")
if(nameDefined(nvpair,cname)) //See if the name is in any pair
{
tvalue=getCookieValue(nvpair,cname) //Gets the value of the cookie
if (tvalue == cvalue) return true
else return false
}
else return false
}
function redirectLink() {
if (testCookie("javahere", "yes")) {
window.location="javahere.html"
}
else{
var futdate = new Date()
var expdate = futdate.getTime()
expdate += 3600*1000 //expires in 1 hour(milliseconds)
futdate.setTime(expdate)
var newCookie="javahere=yes; path=/;"
newCookie += " expires=" + futdate.toGMTString()
window.document.cookie=newCookie
window.location="javanot.html"
}
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<H3>Using an event handler to direct a link based on a cookie value</H3>
<P>
<A NAME="Here" onClick="return redirectLink()">See if you've been here.</A>
</P>
</BODY>
</HTML>
Exercises
Changing Background Color
Javascript makes it possible to change background color of a document dynamically. This means that
you can have terrible visual effects like the one you just saw. Actually, I had planned to make a smooth
shade out sort of thing but somehow, it got like this.
If you specify a background image, then background color will have no effect. So on pages like these, it's
better not to specify a background image.
A scroller is text which scrolls on the status bar of the browser. Take a look at your status bar to
see my scroller. Scrollers are very popular with JavaScript authors (esp. newbies like ourselves)
and equally unpopular with the rest of the Web community
How much programming does it take to create a scroller? Twenty lines, to be exact, as you will
see. But before we go into the code, let us understand what features of JavaScript makes the
scroller possible.
First is the ability to write to the status bar using the window.status property like this:
window.status = "This will appear in the status bar"
The second is the setTimeout() function. This function takes two parameters. The first is a string
specifying the JavaScript statement to be executed on triggering and the second is a number
specifing time in milliseconds after which triggering occurs.
Our scroller is essentially a function which, on each invocation, moves the text on the scroll bar a
little to the left and then calls setTimeout() to invoke itself after a small interval of time.
function Scroller()
{
window.status = scrollText.substring(scrollCounter++,
scrollText.length);
if (scrollCounter == scrollText.length)
scrollCounter = 0;
setTimeout("Scroller()", scrollDelay);
}
Scroller();
// End of scroller script -->
</SCRIPT>
The only other function we use is substring() which is a method of the string object. If
name="JavaScript", then name.substring(4,9) will return "Script". You get the general idea,
right?
If programming is not one of your strong points, you can still have the scroller on your page. Just
copy the above code into your HTML file, preferably between <HEAD> and </HEAD> tags and
change the scrollText and scrollDelay variables in lines 4 & 5 to suit yourself.
This creates a variable called dateVar and initializes it to contain the curent date and time. If you
want to initialize it with some other date and time, you can use any of the following alternate
syntaxes.
You might have come across sites that wish you a Good morning or a Good evening depending
on the time you visit it. This can b e achieved by checking the current time and inserting the
appropriate greeting using the document.write() function. The following code does just that.
You can insert it into an HTML file at the point you wish the greeting to appear.
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide this code from non JavaScript browsers
currentTime = new Date();
if (currentTime.getHours() < 12)
document.write("Good morning");
else if (currentTime.getHours() < 17)
document.write("Good afternoon");
else document.write("Good evening");
A Digital Clock
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide from non JavaScript browsers
function clockTick()
{
currentTime = new Date();
document.clock_form.clock.value = " "+currentTime;
document.clock_form.clock.blur();
setTimeout("clockTick()", 1000);
}
clockTick();
// End of clock -->
</SCRIPT>
</TD></TR>
</TABLE>
The setTimeout() function is discussed in more detail on the Scroller page. The blur()
method is used to remove focus from the Clock textbox.
Using JavaScript, it is possible to program your HTML to display the new icon only for a certain
period of time. You write a JavaScript function which compares the current date with the expiry
date and inserts the new icon only if the current date has not exceded the expiry date. Here is the
code :
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide code from non-js browsers
function newItem(expiryDate)
{
exp = new Date(expiryDate);
cur = new Date();
if (cur.getTime() < exp.getTime())
document.write("<IMG SRC=\"new.gif\" WIDTH=31
HEIGHT=12 BORDER=0 ALT=\"new\">" );
}
// end hiding -->
</SCRIPT>
Usually, functions like this are defined between the <HEAD> and </HEAD> part of the HTML.
Change the new.gif to the name of your image and modify the WIDTH and HEIGHT attributes
accordingly. Now where ever you wan to put the icon, insert the following code :
<SCRIPT LANGUAGE="JavaScript">
<!--
newItem("10/1/96");
// -->
</SCRIPT>
The icon will be shown up to the date you specify as the parameter for newItem().
I am not giving the source code for that because you're better off not doing that to your visitors ;-
Pop-up windows are usually used when you want to display something to the users but you don't
want them to leave the page that they are currently viewing (Perhaps you are afraid that they
might not return). How about a Trivia Game as our next sample. I recently came across this
game and found it very entertaining. You are asked ten questions rapid-fire style, the faster you
answer, the more points you get. If you get more than 1500 points, you qualify for the $25
weekly drawing by registering. So, if you are ready to play, click here.
Note: If you qualify, you might want to maximize the game window to register.
Instead of yes/no values, you may also give 1/0. i.e., you may write toolbar=1 instead of
toolbar=yes.
Here are some combinations that you can try for yourself. All of them open this document in a
new window with different functionalities.
In the above code samples, I have split the code to multiple lines for easier reading but when you
use them, make sure that everything between the double quotes is on a single line.
Creating a form
The following is a form with three fields, a submit button and a reset button.
Date of birth :
The above form was created using HTML code similar to the following :
<FORM NAME="sample" METHOD=POST
ACTION="/cgi-bin/homestead/mail.pl?member_name">
Enter your name : <INPUT TYPE=TEXT NAME="yourname" SIZE=30><BR>
Enter your age : <INPUT TYPE=TEXT NAME="yourage" SIZE=3><BR>
Date of birth : <INPUT TYPE=TEXT NAME="yourdob" SIZE=10><BR>
<INPUT TYPE=SUBMIT> <INPUT TYPE=RESET>
</FORM>
We can refer to this form as document.sample since we have named the form as 'sample'. The
first text field is document.sample.yourname and the second field is
document.sample.yourage. To get the text which is entered in the first text field, you can use
document.sample.yourname.value. Now let us see how to go about validating the data
entered.
To add validation to your form, there are two things that have to be done. The first is to write a
JavaScript routine which does the validation (for this example, we will name the function
validateForm()) and the second is to modify the <FORM> tag to <FORM NAME="sample"
METHOD=POST ACTION="..." onSubmit="return validateForm()"> The above line tells the
browser to call validateForm() when the user submits the form. The following is the code for
validateForm()
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide code from non-js browsers
function validateForm1()
{
formObj = document.sample;
if ((formObj.yourname.value == "") ||
(formObj.yourage.value == "") ||
(formObj.yourdob.value == ""))
{
alert("You have not filled in all the fields.");
return false;
}
else
return true;
}
// end hiding -->
</SCRIPT>
And here is the form with the added validation.
Date of birth :
If any of the fields are blank, an alert box will pop up and the form won't be submitted. The form
is submitted if the validation routine returns a true; if it returns false, the submit operation is
cancelled.
In the preceeding example, the message gave no clue as to which field is actually causing
problems. Usually forms are much bigger and such a message will not be of much use. In the
next form, not only is the message more informative, but the cursor is also placed at the erring
field so that the user can start typing in directly. For example, to position the cursor in the first
field (yourname), we can use the JavaScript function document.sample.yourname.focus().
Here is the modified function.
<SCRIPT LANGUAGE="JavaScript">
<!-- Hide code from non-js browsers
function validateForm()
{
formObj = document.sample;
if (formObj.yourname.value == "")
{
alert("You have not filled in the name field.");
formObj.yourname.focus();
return false;
}
else if (formObj.yourage.value == "")
{
alert("You have not filled in the age field.");
formObj.yourage.focus();
return false;
}
else if (formObj.yourdob.value == "")
{
alert("You have not filled in your date of birth.");
formObj.yourdob.focus();
return false;
}
}
// end hiding -->
</SCRIPT>
Here is our new form.
Date of birth :
Manipulating Images
One of the more interesting things that you can do with JavaScript is playing around with images. To do
this you will need Netscape 3.0+ or IE4.0+.
The folowing example demonstrates how you can change an image dynamically after the page
has finished loading. I use the following two images to do the pseudo-animation.
fanoff.gif fan.gif
When you click on the "On" button, 'fan.gif' is displayed. When you click "Off", 'fanoff.gif' is
displayed. Note that I am only changing the images. The animation happens because 'fan.gif' is
an animated GIF.
<FORM>
<IMG NAME="coolfan" SRC="fanoff.gif"
WIDTH=61 HEIGHT=72><BR><BR>
<INPUT TYPE=BUTTON VALUE=" Off "
onClick="coolfan.src = 'fanoff.gif'">
<INPUT TYPE=BUTTON VALUE=" On "
onClick="coolfan.src = 'fan.gif'">
</FORM>
In the <IMG> tag, the NAME="coolfan" part is added so that we can refer to this image as
coolfan from JavaScript. In the onClick handler of the buttons, we can change the src property of
the image to whatever we want. This will cause the browser to fetch the new image image and
display it in place of the old one.
Image Rollovers
You might have seen a number of web pages where an image transforms when you move the mouse
over it. This can also be done using the above technique. Try moving your mouse over the image below.
Clicking on it will take you to my index.htm page.
Now, take a look at the code required for creating a link like the above one.
I will be putting up some advanced stuff for manipulating images as soon as I learn them myself.
Until then, try experimenting on your own.
You have created your first website but your page counter is not counting as fast as you thought
it would. The only people who visit seem to be your mom and your best friend. Mothers
understand but how do you explain this phenomena to your friend. It's simple really. Just
password protect your site. Although this won't increase the number of visitors, you can use it
explain why the numbers are not in the millions.
My first attempt at password protecting went something like this: Replace the page you want to
protect with another page that would ask the visitor for a username and password. When the
visitor clicks submit, the Javascript code on the page checks whether the username and password
match and redirect the visitor to the original page.The code is given below.
<FORM NAME="login">
Username: <INPUT NAME="username"><BR>
Password: <INPUT NAME="password" TYPE=PASSWORD><BR>
<INPUT TYPE=BUTTON VALUE="Login" onClick="verifyLogin()">
<INPUT TYPE=RESET>
</FORM>
<SCRIPT LANGUAGE="Javascript">
<!--
function verifyLogin()
{
var myForm = document.login;
It's pretty stright forward and it works. The only problem is that anyone can do a View|Source
and find out your username and password and also the address of the password protected page,
and that obviously is not good.
What we need is a method in which looking at the HTML source will reveal nothing about the
username, password or the target page. One such method that is commonly used is to generate
the target page name from what the user enters in the username and password fields and redirect
the browser to that page. Take a look at the modified verifyLogin() function.
<SCRIPT LANGUAGE="Javascript">
<!--
function verifyLogin()
{
var myForm = document.login;
window.location.href = myForm.username.value +
myForm.password.value +
".html";
}
// -->
</SCRIPT>
All that the function now does is to concatenate the username, the password and ".html" and
redirect the browser to that location. So if your visitor entered secret as the username and page as
the password, he/she would be taken to secretpage.html. If on the other hand, they don't know
the correct username and password and entered say foo as the username and bar as the password,
they would be redirected to the non-existant foobar.html and get an error saying that the page
was not found.
There is another reason for wanting to password protect your pages other than the one mentiond
at the beginning of this page, and that is you actually have something that you don't want to make
public. My advice to you is do not use Javascript based password protection schemes.