PDA

Click to See Complete Forum and Search --> : Preload an image before javascript is enabled?


Dec 29th, 2000, 09:20 PM
I am using javascript to replace an image using onMouseOver and I was wondering if there is a way to preload that image before the user gets the effect. It seems that the first time the page is loaded, when none of the graphics are cached, when you put the mouse over it, it hesitates as the browser goes and gets the image. Once the browser gets the image, it works perfectly, but it is just the first time that is bugging me.


Is there a way to do this?

Dec 30th, 2000, 05:54 AM
<HTML>
<HEAD>
<SCRIPT>
<!--
img1 = new Image (); //this is the
img1.src = "pic1.gif"; //part that
img2 = new Image (); //preloads the
img2.src = "pic2.gif"; //images

function up()
{
document.mypic.src=img1.src;
}

function down()
{
document.mypic.src=img2.src;
}
-->
</SCRIPT>
</HEAD>
<BODY>
<IMG SRC="pic1.gif" NAME="mypic" onMouseOver="down()" onMouseOut="up()">
</BODY>
</HTML>

Kagey
Dec 30th, 2000, 10:02 AM
Try this if you have more than 1 rollover on a page, so you dont have to create a function for each up and down instance.

Example: You have two images: img1 and img2.
Img2 will show when user moves mouse over a link that uses IMG1.

So, first write the following in the <HEAD> section:


<HEAD>

<SCRIPT>

img1 = new Image();
img1.src = "images/img1.gif";
img2 = new Image();
img2.src = "images/img2.gif";

function hilite(imgDocID,imgObjName)
{
document.images[imgDocID].src = eval(imgObjName + ".src")
}

</SCRIPT>
</HEAD>


So, here, first four lines preloads images and function "hilite" will change one image to another in your code. First param of this function is NAME of IMAGE object <IMG NAME="...">, and the second param is a name of preloaded image (img1 or img2).

This is example:

<a href="anything.html" OnMouseOver="hilite('img','img2');" OnMouseOut="hilite('img','img1');">
<img src=img1.gif border=0 name="img"></a>


So, here "img" is a name of image object.

Let me know how you fare.