Javascript onmouseover image switch

I’m using the following to switch an image on hover:

<img src=“/ico/view.jpg” onmouseover=“this.src=‘/ico/view.hover.jpg’” onmouseout=“this.src=‘/ico/view.jpg’” />

and the following to preload the images to switch:

var preload = [“a.jpg”, “b.jpg”, “c.jpg”];
var images = ;
for (i = 0; i < preload.length; i++) {
images[i] = new Image();
images[i].src = preload[i];
}

The images being switched to appear a little blurry even though I can open the same images directly in the browser and they appear sharp. There is also a delay once in a while even though the images are being preloaded. Does anyone know why this is happening?

Are there any caveats or drawbacks to doing this that I should be aware of? I haven’t used Javascript before. I did notice the preload doesn’t seem to work with a “cache killer” enabled in the browser.

Hi there,

I would do it like this:

<!DOCTYPE HTML>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Unbenanntes Dokument</title>
  </head>
  
  <body>
  
    <img id="myImage" src="http://3.bp.blogspot.com/_ss1KeGx9Bng/THgWaTaHhuI/AAAAAAAAAB0/3PLmvniAdNk/s1600/lolcats_oh-noes_ihasletgo.jpg">
    
    <script>
      var img = document.getElementById("myImage"),
          img2=new Image(),
          originalSrc = img.src;      

      img2.src="https://i.chzbgr.com/maxW500/6073452544/h4B353A81/";
      
      img.onmouseover = function(){
        document.getElementById('myImage').src=img2.src;
      }
      
      img.onmouseout = function(){
        document.getElementById('myImage').src=originalSrc;
      }
    </script>
  </body>
</html>

Does that help any?

Thank you I will try that.

I don’t see the blurring issue any more. When preloading images like this, should the hover effect always be really fast and snappy? I’m seeing some pretty significant lag for some images, even after hovering over the same image multiple times. Should that be happening?

Were you maybe specifying an incorrect image size in the image tag?
e.g. <img width=“200” height=“200” src=“…” />

Absolutely.

No.
If you can post a demo page, I don’t mind having a look at it for you.