Results 1 to 3 of 3

Thread: Preload an image before javascript is enabled?

  1. #1
    Guest
    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?

  2. #2
    Guest
    Code:
    <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>

  3. #3
    Hyperactive Member Kagey's Avatar
    Join Date
    Sep 2000
    Location
    The Wilderness of New Brunswick
    Posts
    294
    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:

    Code:
    <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:
    Code:
    <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.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width