sivaramaiah  
 
  JavaScript2 04/25/2024 5:18pm (UTC)
   
 

The statusbar

Your JavaScript programs can write to the statusbar - this is the bar at the bottom of your browser

window. All you have to do is to assign a string to window.status. The following example

shows you two buttons which can be used to write to the statusbar and to erase the text again.

(The online version lets you test this script immediately)

<html>

<head>

<script language="JavaScript">

<!-- hide

function statbar(txt) {

window.status = txt;

}

// -->

</script>

</head>

<body>

<form>

<input type="button" name="look" value="Write!"

onClick="statbar('Hi! This is the statusbar!');">

<input type="button" name="erase" value="Erase!"

onClick="statbar('');">

</form>

</body>

</html>

We create a form with two buttons. Both buttons call the function

the function call created by the

statbar(). You can see thatWrite! button looks like this:

statbar('Hi! This is the statusbar!');

Inside the brackets we specify the string ’

alond to the function

Hi! This is the statusbar!’ This means this string is passedstatbar(). You can see that we defined the function statbar() like this:

function statbar(txt) {

window.status = txt;

}

What is new is that we use

we passed along to the function is stored in the variable

often used way for making functions more flexible. You can pass several values to functions -

you just have to separate them through commas. The string

through

empty string to

Displaying text on the statusbar can easily be used in combination with links. Instead of

showing the URL of the link you can explain in words what the next page is about. This link

demonstrates this - just move your mousepointer over the link. The code for this example looks

like this:

txt inside the brackets of the function name. This means the stringtxt. Passing variables to functions is antxt is displayed on the statusbarwindow.status = txt. Erasing the text on the statusbar is achived through assigning anwindow.status.

<a href="dontclck.htm"

onMouseOver="window.status=’Don\’t click me!’; return true;"

onMouseOut="window.status=’’;">link</a>

Here we are using

moves across the link. You might wonder why we have to write return true inside the

MouseOver

the

do not use

executed - this means it would overwrite our text and the user couldn’t read it. In general we can

suppress the following actions of the browser by using return true in the event-handler.

onMouseOver and onMouseOut in order to detect when the mousepointeron-property. This means that the browser won’t execute its own code as a reaction toMouseOver event. Normally the browser displays the URL of the link in the statusbar. If wereturn true the browser will write to the statusbar immediately after our code has been

onMouseOut

might get different results on different platforms. On Unix platforms for example the text dissapears

even though the browser does not know onMouseOut. On Windows the text does not

dissapear. If you want your script to be compatible to Netscape 2.x on Windows you might for

example write a function which writes text to the statusbar and erases this text after a certain

period of time. This is programmed with a timeout. We will learn more about timeouts in the

following paragraph.

In this script you can see another thing - sometimes you want to output quotes. We want to output

the text

are using the single quotes. But the word

mixed up if you just write

the quote - which means that it belongs to the output (you can do the same with double quotes

").

did not exist in JavaScript 1.0. If you are using the Netscape Navigator 2.x youDon’t click me - as we specify this string inside the onMouseOver event-handler weDon’t uses a single quote as well! The browser gets’Don’t ...’. To solve this problem you can just write a backslash \ before

Timeouts

With the help of timeouts (or timer) you can let the computer execute some code after a certain

period of time. The following script shows a button which opens up a popup window after 3

seconds.

The script looks like this:

<script language="JavaScript">

<!-- hide

function timer() {

setTimeout("alert(’Time is up!’)", 3000);

}

// -->

</script>

...

<form>

<input type="button" value="Timer" onClick="timer()">

</form>

setTimeout()

that. The first argument is the JavaScript code which shall be executed after a certain time.

In our case this argument is

inside quotes. The second argument tells the computer when the code shall be executed. You

have to specify the time in number of milliseconds (3000 milliseconds = 3 seconds).

is a method of the window-object. It sets a timeout - I think you might have guessed"alert(’Time is up!’)". Please note that the JavaScript code has to be

Scroller

Now that you know how to write to the statusbar and how timeouts work we will have a look at

scrollers. You might already know the moving text-strings in the statusbar. They can be seen all

over the Internet. We will see how to program a basic scroller. Besides that we will think of possible

improvements of the scroller. Scrollers are quite easy to implement. Just let us think about

how we could realize a moving text in the statusbar. We have to write a text to the statusbar.

After a short period of time we have to write the same text to the statusbar - but we have to move

it a little bit to the left side. If we repeat this over and over again the user gets the impression of

a moving text. We have to think about how we can determine which part of the text should be

displayed as the whole text is normally longer than the statusbar.

(The online version lets you test this script immediately)

Here is the source code - I have added some comments:

<html>

<head>

<script language="JavaScript">

<!-- hide

// define the text of the scroller

var scrtxt = "This is JavaScript! " +

"This is JavaScript! " +

"This is JavaScript!";

var length = scrtxt.length;

var width = 100;

var pos = -(width + 2);

function scroll() {

// display the text at the right position and set a timeout

// move the position one step further

pos++;

// calculate the text which shall be displayed

var scroller = "";

if (pos == length) {

pos = -(width + 2);

}

// if the text hasn’t reached the left side yet we have to

// add some spaces - otherwise we have to cut of the first

// part of the text (which moved already across the left border

if (pos < 0) {

for (var i = 1; i <= Math.abs(pos); i++) {

scroller = scroller + " ";}

scroller = scroller + scrtxt.substring(0, width - i + 1);

}

else {

scroller = scroller + scrtxt.substring(pos, width + pos);

}

// assign the text to the statusbar

window.status = scroller;

// call this function again after 100 milliseconds

setTimeout("scroll()", 100);

}

// -->

</script>

</head>

<body onLoad="scroll()">

Your HTML-page goes here.

</body>

</html>

The main part of the

displayed. I am not explaining the code in detail - you just have to understand how this scroller

works in general. In order to start the scroller we are using the onLoad event-handler of the

scroll() function is needed for calculating which part of the text is being<body>

tag. This means the function

loaded. We call the

being calculated and displayed. At the end of the

the

and another timeout is set. This goes on for ever.

(There have been some problems with this kind of scroller with Netscape Navigator 2.x. It sometimes

caused an ’Out of memory’-error. I’ve got many mails explaining this is because of the

recursive call of the scroll() function - finally leading to a memory overflow. But this is not true.

This is not a recursive function call! We get recursion if we call the scroll() function inside the

scroll() function itself. But this isn’t what we are doing here. The old function which sets the

timeout is finished before the new function is executed. The problem was that strings could not

really be changed in JavaScript. If you tried to do it JavaScript simply created a new object -

without removing the old one. This is what filled up the memory.)

Scrollers are used widely in the Internet. There is the risk that they get unpopular quickly. I must

admit that I do not like them too much. Especially annoying on most pages is that the URL

cannot be read anymore when moving the pointer across a link. This can be solved through stopping

the scroller when a MouseOver event occurs - you can start it again with onMouseOut. If

you want to have a scroller try not to use the standard scroller - try to add some nice effect. Maybe

one part of the text moving from left and the other part is coming from right - when they meet

in the middle the text stands still for some seconds. With some phantasy you can certainly find

some nice alternatives (I have some examples in my book).

scroll() will be called right after the HTML-page has beenscroll() function with the onLoad property. The first step of the scroller isscroll() function we set a timeout. This causesscroll() function to be executed again after 100 milliseconds. The text is moved one step forward

©1996,1997 by Stefan Koch

e-mail:skoch@rumms.uni-mannheim.de

http://rummelplatz.uni-mannheim.de/~skoch/

My JavaScript-book: http://www.dpunkt.de/javascript

V

OODOOS INTRODUCTION TO JAVASCRIPT

© 1996, 1997 by Stefan Koch

Part 6: Predefined objects

The Date-object

JavaScript lets you use some predefined objects. This is for example the Date-object, the Arrayobject

or the Math-object. There are several other objects - please refer to the documentation

provided by Netscape for a complete reference.

We are going to have a look at the Date-object first. As the name implies this object lets you

work with time and date. For example you can easily calculate how many days are left until next

christmas. Or you can add the actual time to your HTML-document.

So let’s begin with an example which displays the actual time. First we have to create a new

Date-object. For this purpose we are using the new operator. Look at this line of code:

today= new Date()

This creates a new Date-object called today. If you do not specify a certain date and time when

creating a new Date-object the actual date and time is used. This means after executing

new Date()

The Date-object offers some methods which can now be used with our object today. This is for

example

You can find a complete reference of the Date-object and its methods in Netscapes JavaScript

documentation.

Please note that a Date-object does only represent a certain date and time. It is not like a clock

which changes the time every second or millisecond automatically.

In order to get another date and time we can use another constructor (this is the

which is called through the

today=the new Date-object today represents the date and time of this specific moment.getHours(), setHours(), getMinutes(), setMinutes(), getMonth(), setMonth() and so on.Date() methodnew operator when constructing a new Date-object):

today= new Date(1997, 0, 1, 17, 35, 23)

This will create a Date-object which represents the first of january 1997 at 17:35 and 23 seconds.

So you specify the date and time like this:

Date(year, month, day, hours, minutes, seconds)

Please note that you have to use 0 for january - and not 1 as you might think. 1 stands for february

and so on.

Now we will write a script which outputs the actual date and time. The result will look like this:

Time: 17:53

Date: 4/3/2010

The code looks like this:

<script language="JavaScript">

<!-- hide

now= new Date();

document.write("Time: " + now.getHours() + ":" + now.getMinutes() + "<br>");

document.write("Date: " + (now.getMonth() + 1) + "/" + now.getDate() + "/" +

(1900 + now.getYear()));

// -->

</script>

Here we use methods like

now. You can see that we are adding 1900 to the year. The method

number of years since 1900. This means if the year is 1997 it will return 97 if the year is 2010

it will return 110 - not 10! If we add 1900 we won’t have the year 2000 problem. Remember that

we have to increment the number we receive through

This script does not check whether the number of minutes is less than 10. This means you can

get a time which looks like this:

how to solve this problem.

Now we will have a look at a script which displays a working clock:

getHours() in order to display the time and date specified in out DateobjectgetYear() returns thegetMonth() by one.14:3 which actually means 14:03. We will see in the next script

<html>

<head>

<script Language="JavaScript">

<!-- hide

var timeStr, dateStr;

function clock() {

now= new Date();

// time

hours= now.getHours();

minutes= now.getMinutes();

seconds= now.getSeconds();

timeStr= "" + hours;

timeStr+= ((minutes < 10) ? ":0" : ":") + minutes;

timeStr+= ((seconds < 10) ? ":0" : ":") + seconds;

document.clock.time.value = timeStr;

// date

date= now.getDate();

month= now.getMonth()+1;

year= now.getYear();

dateStr= "" + month;

dateStr+= ((date < 10) ? "/0" : "/") + date;

dateStr+= "/" + year;

document.clock.date.value = dateStr;

Timer= setTimeout("clock()",1000);

}

// -->

</script>

</head>

<body onLoad="clock()">

<form name="clock">

Time:

<input type="text" name="time" size="8" value=""><br>

Date:

<input type="text" name="date" size="8" value="">

</form>

</body>

</html>

(The online version lets you test this script immediately)

We use the

second a new Date-object with the actual time. You can see that the function

with the

two text-elements. The function

in the right format. You can see that we are using two strings

We have mentioned earlier that there is a problem with minutes less than 10 - this script solves

this problem through this line of code:

setTimeout() method for setting the time and date every second. So we create everyclock() is calledonLoad event-handler in the <body> tag. In the body-part of our HTML-page we haveclock() writes the time and date into these two form-elementstimeStr and dateStr for this purpose.

timeStr+= ((minutes < 10) ? ":0" : ":") + minutes;

Here the number of minutes are added to the string

have to add a 0. This line of code might look a little bit strange to you. You could also write it

like this which might look more familar:

timeStr. If the minutes are less than 10 we

if (minutes < 10) timeStr+= ":0" + minutes

else timeStr+= ":" + minutes;

The Array-object

Arrays are very important. Just think of an example where you want to store 100 different names.

How could you do this with JavaScript? Well, you could define 100 variables and assign

the different names to them. This is quite complicated.

Arrays can be seen as many variables bundled together. You can access them through one name

and a number.

Let’s say out array is called

second name is called

Since JavaScript 1.1 (Netscape Navigator 3.0) you can use the Array-object. You can create a

new array through

names. Then we can access the first name through names[0]. Thename[1] and so on.myArray= new Array(). Now you can assign values to this array:

myArray[0]= 17;

myArray[1]= "Stefan";

myArray[2]= "Koch";

JavaScript arrays are really flexible. You do not have to bother about the size of the array - its

size is being set dynamically. If you write

(a JavaScript array can only grow - it hasn’t got the ability to shrink. So keep your arrays

as small as possible.). It doesn’t matter if you store numbers, strings or other objects in an array.

I haven’t mentioned every detail of arrays here but I hope you will see that arrays are a very important

concept.

Certainly many things get clearer by looking at an example. The output of the following example

is:

myArray[99]= "xyz" the size of the array get 100 elements

first element

second element

third element

Here is the source code:

<script language="JavaScript">

<!-- hide

myArray= new Array();

myArray[0]= "first element";

myArray[1]= "second element";

myArray[2]= "third element";

for (var i= 0; i< 3; i++) {

document.write(myArray[i] + "<br>");

}

// -->

</script>

First we are creating a new array called

array. After this we start a loop. This loop executes the command

+ "<br>");

we are using

myArray. Then we assign three different values to thedocument.write(myArray[i]three times. The variable i counts from 0 to 2 with this for-loop. You can see thatmyArray[i] inside the for-loop. As i counts from 0 to 2 we get three document.write()

calls. We could rewrite the loop as:

document.write(myArray[0] + "<br>");

document.write(myArray[1] + "<br>");

document.write(myArray[2] + "<br>");

Arrays with JavaScript 1.0

As the Array-object does not exist in JavaScript 1.0 (Netscape Navigator 2.x and Microsoft Internet

Explorer 3.x) we have to think of an alternative. This piece of code could be found in the

Netscape documentation:

function initArray() {

this.length = initArray.arguments.length

for (var i = 0; i < this.length; i++)

this[i+1] = initArray.arguments[i]

}

You can now create an array with:

myArray= new initArray(17, 3, 5);

The numbers inside the brackets are the values the array is being initialized with (this can also

be done with the Array-object from JavaScript 1.1). Please note that this kind of array does not

implement all elements the Array-object from JavaScript 1.1 has (there is for example a sort()

method which lets you sort all elements in a specific).

The Math-object

If you need to do mathematical calculations you will find some methods in the Math-object

which might help you further. There is for example a sine-method

reference in the Netscape documentation. I want to demonstrate the

you have read the first version of this tutorial you know that there have been some problems

with the

need that anymore as the

If you call

output of

sin(). You will find a completerandom() method. Ifrandom() method. We wrote a function which let us create random numbers. We don’trandom() method now works on all platforms.Math.random() you will receive a random number between 0 and 1. Here is one possibledocument.write(Math.random()):

.7184317731538611

©1996,1997 by Stefan Koch

e-mail:skoch@rumms.uni-mannheim.de

http://rummelplatz.uni-mannheim.de/~skoch/

My JavaScript-book: http://www.dpunkt.de/javascript

V

OODOOS INTRODUCTION TO JAVASCRIPT

© 1996, 1997 by Stefan Koch

Part 7: Forms

Validating form input

Forms are widely used on the Internet. The form input is often being sent back to the server or

via mail to a certain e-mail account. But how can you be certain that a valid input was done by

the user? With the help of JavaScript the form input can easily be checked before sending it over

the Internet. First I want to demonstrate how forms can be validated. Then we will have a look

at the possibilties for sending information over the Internet.

First of all we want to create a simple script. The HTML-page shall contain two text-elements.

The user has to write his name into the first and an e-mail address into the second element. If

the user has entered his name (for example ‘

popup window with the text ‘

Stefan’) into the first text-field the script creates aHi Stefan!’.

(The online version lets you test this script immediately)

Concerning the first input element you will receive an error message when nothing is entered.

Any input is seen as valid input. Of course, this does not prevent the user from entering any

wrong name. The browser even accepts numbers. So if you enter '

this might not be a good check. The second form is a little bit more sophisticated. Try to enter

a simple string - your name for example. It won't work (unless you have a @ in your name...).

The criteria for accepting the input as a valid e-mail address is the @. A single @ will do it - but

this is certainly not very meaningful. Every Internet e-mail address contains a @ so it seems appropriate

to check for a @ here.

What does the script for those two form elements and for the validating look like? Here it goes:

17' you will get 'Hi 17!'. So

<html>

<head>

<script language="JavaScript">

<!-- Hide

function test1(form) {

if (form.text1.value == "")

alert("Please enter a string!")

else {

alert("Hi "+form.text1.value+"! Form input ok!");

}

}

function test2(form) {

if (form.text2.value == "" ||

form.text2.value.indexOf(’@’, 0) == -1)

alert("No valid e-mail address!");

else alert("OK!");

}

// -->

</script>

</head>

<body>

<form name="first">

Enter your name:<br>

<input type="text" name="text1">

<input type="button" name="button1" value="Test Input" onClick="test1(this.form)">

<P>

Enter your e-mail address:<br>

<input type="text" name="text2">

<input type="button" name="button2" value="Test Input" onClick="test2(this.form)">

</body>

</html>

First have a look at the HTML-code in the body-section. We just create two text elements and

two buttons. The buttons call the functions

pressed. We pass this.form to the functions in order to be able to address the right elements in

the functions later on. The function test1(form) tests if the string is empty. This is done via

(form.text1.value == "")...

function call. We can get the value of the input element through using ’

with

equals "" then no input was done. The user will get an error message. If something is entered

the user will get an ok.

The problem here is that the user might enter only spaces. This is seen as a valid input! If you

want to, you can of course check for these possibilities and exclude them. I think this is quite

easy with the information given here. Now have a look at the

again compares the input string with the empty string "" to make sure that something has been

entered. But we have added something to the if-command. The || is called the OR-operator. You

have learned about it in part 6 of this introduction. The if-command checks if either the first or

the second comparison is true. If at least one of them is true the whole if-command gets

the following command will be executed. This means that you will get an error message either

if your string is empty or if there isn’t a @ in your string. The second operation in the if-command

looks if the entered string contains a @.

test1(...) or test2(...) depending on which button isif. ’form’ is the variable which receives the ’this.form’ value in thevalue’ in combinationform.text1. In order to look if the string is empty we compare it with "". If the input stringtest2(form) function. This functiontrue and

Checking for certain characters

Sometimes you want to restrict the form input to certain characters or numbers. Just think of a

telephone number - the input should only contain digits (we assume that the telephone number

does not contain any characters). We could check if the input is a number. But most people use

different symbols in their telephone number - for example:

01234-56789

forced to enter the telephone number without these symbols. So we have to extend our script to

check for digits and some symbols. This is demonstrated in the next example which is taken

from my JavaScript book:

, 01234/56789 or 01234 56789 (with a space inbetween). The user should not be

(The online version lets you test this script immediately)

<html>

<head>

<script language="JavaScript">

<!-- hide

// ******************************************************

// Script from Stefan Koch - Voodoo’s Intro to JavaScript

// http://rummelplatz.uni-mannheim.de/~skoch/js/

// JS-book: http://www.dpunkt.de/javascript

// You can use this code if you leave this message

// ******************************************************

function check(input) {

var ok = true;

for (var i = 0; i < input.length; i++) {

var chr = input.charAt(i);

var found = false;

for (var j = 1; j < check.length; j++) {

if (chr == check[j]) found = true;

}

if (!found) ok = false;

}

return ok;

}

function test(input) {

if (!check(input, "1", "2", "3", "4",

"5", "6", "7", "8", "9", "0", "/", "-", " ")) {

alert("Input not ok.");

}

else {

alert("Input ok!");

}

}

// -->

</script>

</head>

<body>

<form>

Telephone:

<input type="text" name="telephone" value="">

<input type="button" value="Check"

onClick="test(this.form.telephone.value)">

</form>

</body>

</html>

The function

test() specifies which characters are valid.

Submitting form input

What different possibilities do exist for submitting form input? The easiest way is to submit the

form input via e-mail. This is the method we are going to look at a little bit closer. If you want

the form input to be handled by the server you need to use CGI (Common Gateway Interface).

This allows you to process the form input automatically. The server might for example build up

a database from the input received by some customers. Another example are index-pages like

Yahoo. They usually have a form for making a search in their database. The user gets a response

quickly after the submit button was hit. He does not have to wait until the people maintaining

this server read the input and then look up the information requested. This is done

automatically by the server. JavaScript cannot do things like this. You cannot create guestbooks

with JavaScript because JavaScript isn’t able to write to a file on the server. You can only do

this through CGI. Of course you can create a guestbook with the people answering via e-mail.

You have to enter the feedback manually though. This is ok if you don’t expect to get 1000 feedback

mails a day.

This script here is plain HTML. So no JavaScript is needed here! Only, of course, if you want

to check the input before the form is submitted you will need JavaScript. I have to add that the

mailto-command does not work everywhere - for example the Microsoft Internet Explorer 3.0

does not support it.

<form method=post action="mailto:your.address@goes.here" enctype="text/plain">

Do you like this page?

<input name="choice" type="radio" value="1">Not at all.<br>

<input name="choice" type="radio" value="2" CHECKED>Waste of time.<br>

<input name="choice" type="radio" value="3">Worst site of the Net.<br>

<input name="submit" type="submit" value="Send">

</form>

The property

makes it much easier to read the mail.

If you want to validate the form before it is sent over the net you can use the onSubmit eventhandler.

You have to put this event-handler into the

enctype="text/plain" is used in order to send plain text without encoded parts. This<form> tag. This looks like this:

function validate() {

// check if input ok

// ...

if (inputOK) return true

else return false;

}

...

<form ... onSubmit="return validate()">

...

With this code the form isn’t being sent over the Internet if the form input was wrong.

Setting the focus to a certain form-element

With the help of the

can define which element is in focus at the beginning. Or you could tell the browser to focus on

the form where the input was wrong. This means that the browser will set the cursor into the

specified form-element so the user does not have to click on the form before entering anything.

You can do this with the following piece of script:

focus() method you can make your form a little bit more user-friendly. You

function setfocus() {

document.first.text1.focus();

}

This script would set the focus to the first text-element in the script I have shown above. You

have to specify the name of the whole form - which is called first here - and the name of the

single form element - here

being loaded you can add an onLoad-property to your

text1. If you want to put the focus on this element when the page is<body> tag. This looks like this:

<body onLoad="setfocus()">

We can extend this with the following code:

function setfocus() {

document.first.text1.focus();

document.first.text1.select();

}

(The online version lets you test this script immediately)

The text-element gets the focus and the text contained in this text-element is being selected.

©1996,1997 by Stefan Koch

e-mail:skoch@rumms.uni-mannheim.de

http://rummelplatz.uni-mannheim.de/~skoch/

My JavaScript-book: http://www.dpunkt.de/javascript

V

OODOOS INTRODUCTION TO JAVASCRIPT

© 1996, 1997 by Stefan Koch

Part 8: The Image-object

Images on a web-page

Now we are going to have a look at the Image-object which is available since JavaScript 1.1 (i.e.

since Netscape Navigator 3.0). With the help of the Image-object you can change images on a

web-page. This allows us for example to create animations.

Please note that users of older browsers (like Netscape Navigator 2.0 or Microsoft Internet Explorer

3.0 - they use JavaScript 1.0) cannot run the scripts shown in this part - or at least they

cannot see the whole effect. First, let’s see how the images in a web-page can be addressed

through JavaScript. All images are represented through an array. This array is called images. It

is a property of the document-object. Every image on a web-page gets a number. The first image

gets the number 0, the second image gets the number 1 and so on. So we can address the first

image through document.images[0].

Every image in an HTML-document is considered as an Image-object. An Image-object has got

certain properties which can be accessed through JavaScript. You can for example see which

size an image has with the properties

width (in pixel) of the first image on the web-page.

Especially if you have many images on one page it gets hard to keep count of all images. Giving

names to the different images solves this problem. If you declare an image with this tag

width and height. document.images[0].width gives you the

<img src="img.gif" name="myImage" width=100 height=100>

you can address it through

document.myImage or document.images["myImage"].

Loading new images

Although it is nice to know how to get the size of an image on a web-page this is not what we

wanted to know. We want to change images on a web-page. For this purpose we need the

src

property. As in the

With JavaScript 1.1 you can now assign new addresses to an already loaded image on a webpage.

The result is that the image located at the new address is being loaded.

This new image replaces the old image on the web-page. Look at this example:

<img> tag the src property represents the address of the displayed image.

<img src="img1.gif" name="myImage" width=100 height=100>

The image

the old image

img1.gif is being loaded and gets the name myImage. The following line of code replacesimg1.gif with the new image img2.gif:

document.myImage.src= "img2.src";

The new image has always got the same size as the old image. You cannot change the size of

the area in which the image is being displayed.

(The online version lets you test this script immediately)

Preloading images

One drawback might be that the new image gets loaded after assigning a new address to the src

property. As the image is not preloaded it takes some time until the new image is retrieved

through the Internet. In some situations this is ok - but often these delays are not acceptable. So

what can we do about this? Yes, preloading the image is the solution. For this purpose we have

to create a new Image-object. Look at these lines of code:

hiddenImg= new Image();

hiddenImg.src= "img3.gif";

The first line creates a new Image-Object. The second line defines the address of the image

which shall be represented through the object hiddenImg. We have already seen that assigning

a new address to the

So the image img2.gif gets loaded when the second line of this code is being executed. As the

name hiddenImg implies the image is not being displayed after the browser finished loading it.

It is just kept in the memory (or better in the cache) for later use. In order to display this image

we can now use this line:

src attribute forces the browser to load the image the address is pointing at.

document.myImage.src= hiddenImg.src;

Now the image is being taken from the cache and displayed immediately. We have managed to

preload the image. Of course the browser must have finished the preloading for being able to

display an image without delay. So if you have many images specified for preloading there

might be a delay nevertheless because the browser has been busy to download all the other pictures.

You always have to consider the speed of the Internet - the downloading of the images

doesn’t go faster with this code shown here. We only try to start the downloading of the images

earlier - so the user can see them earlier. This makes the whole process much smoother.

If you have a fast Internet connection you might wonder what all this talk is about. Which delay

is this guy talking about all the time? Well, there are still some people sitting behind a 14.4 modem

(No, not me. I just upgraded to 33.6 - oh yes...).

Changing images on user-initiated events

You can create nice effects through changing images as a reaction to certain events. You can for

example change images when the mouse cursor is being moved over a certain area.

(The online version lets you test this script immediately)

The source code for this example looks like this:

<a href="#"

onMouseOver="document.myImage2.src=’img2.gif’"

onMouseOut="document.myImage2.src=’img1.gif’">

<img src="img1.gif" name="myImage2" width=160 height=50 border=0></a>

This code causes some problems though:

- The user might not use a JavaScript 1.1 browser.

- The second image is not being preloaded.

- We have to rewrite the code for every image on a web-page.

- We want to have a script which can be used in many web-page over and over again

without large changes.

We will now have a look at a complete script which solves these problems. The script gets much

longer - but once it is written you do not have to bother about it anymore. There are two requirements

for keeping the script flexible:

- Undefined number of images - it should not matter if 10 or 100 images are used

- Undefined order of images - it should be possible to change the order of the images

without changing the code

(The online version lets you test this script immediately)

Have a look at the code (I have added some comments):

<html>

<head>

<script language="JavaScript">

<!-- hide

// ******************************************************

// Script from Stefan Koch - Voodoo’s Intro to JavaScript

// http://rummelplatz.uni-mannheim.de/~skoch/js/

// JS-book: http://www.dpunkt.de/javascript

// You can use this code if you leave this message

// ******************************************************

// ok, we have a JavaScript browser

var browserOK = false;

var pics;

// -->

</script>

<script language="JavaScript1.1">

<!-- hide

// JavaScript 1.1 browser - oh yes!

browserOK = true;

pics = new Array();

// -->

</script>

<script language="JavaScript">

<!-- hide

var objCount = 0; // number of (changing) images on web-page

function preload(name, first, second) {

// preload images and place them in an array

if (browserOK) {

pics[objCount] = new Array(3);

pics[objCount][0] = new Image();

pics[objCount][0].src = first;

pics[objCount][1] = new Image();

pics[objCount][1].src = second;

pics[objCount][2] = name;

objCount++;

}

}

function on(name){

if (browserOK) {

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

if (document.images[pics[i][2]] != null)

if (name != pics[i][2]) {

// set back all other pictures

document.images[pics[i][2]].src = pics[i][0].src;

} else {

// show the second image because cursor moves across this image

document.images[pics[i][2]].src = pics[i][1].src;

}

}

}

 
  Menu Items
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

  add
HOT TOPICS
MCA PROJECT DETAILS ------------------------------------- Jntu all Lab manuals ------------------------------------- Jntu Syllabus Books ------------------------------------- Paper presentations ------------------------------------- Seminars ------------------------------------- Campus Papers ------------------------------------- Competetive Exams GATE ------------------------------------- GRE ------------------------------------- TOEFL ------------------------------------- IELTS ------------------------------------- CAT ------------------------------------- GMAT ------------------------------------- Templates ------------------------------------- Students Resume Preparation tips ------------------------------------- Job zone(Interview questions) ------------------------------------- Google Adsence html code ------------------------------------- Web sites --------x--------------x-----------
  Advertisement

 


-----------------------------
  Offline Messages
  Adds
  Visitors Information
Today, there have been 119840 visitors (281756 hits) on this page!
-------------------------------------------------- This website was created for free with Own-Free-Website.com. Would you also like to have your own website?
Sign up for free