What a surprise that Internet Explorer is STILL giving website designers problems. Ok, so it’s actually NOT a surprise, but definitely still a timewaster.
The latest issue I was trying to resolve was one of the simplest things to add to my website: an image change on mouseover. I’ve been doing this with some lengthy javascript for years, but now I wanted to simplify my code and do it within my jQuery document.ready function. Should be simple right? Well, it is … except for the fact that Internet Explorer keeps reloading images every time you hover over them. After a bit of research I found that MSIE just drops images from its cache that aren’t in the DOM and so I first tried tricks to stop that (including a CSS filter), but they didn’t work.
Finally, after reading countless websites where people were discussing the same issue and trying their solutions, I found the answer. Not by reading it in any one place, but by just trying something myself. Here’s the solution: Preload the images, and append them to the DOM so MSIE won’t discard them. The difference is you must preload and append ALL the images: both your intitial images as well as the “hover” images. Every site I went to mentioned preloading the “hover” images but not the initial ones. The reason MSIE threw them away was because I was using the “replace” function which basically unloaded one image from the DOM and put a different one in. At least that’s what I’m thinking was the issue.
So, the following is what you should be doing if you want your images to pre-load and change out on hover … and work in ALL browsers including MSIE. Place this within your $(document).ready(function(){ tree:
function preload(arrayOfImages) { $(arrayOfImages).each(function () { $('<img />').attr('src',this).appendTo('body').css('display','none'); }); } // list ALL your images in this array - both "on" and "off" preload([ "images/hoverImage1_on.png", "images/hoverImage2_on.png", "images/hoverImage1_off.png", "images/hoverImage2_off.png" ]); // attach the replace function to the proper element $(".linkbutton").hover( function(){this.src = this.src.replace("_off","_on");}, function(){this.src = this.src.replace("_on","_off"); });
That’s it! Hopefully this will save you some time and stop you from pulling out your hair as it did me. Thanks to the sites I went to with the code I pieced together for this.