Time for a snippet of code on this blog I reckon. The other day I wanted a simple JQuery rollover mechanism for some in-markup images, but after a bit of a hunt I gave up as the only preload machanisms I could find involved a whole plugin or knowing the names of all the images on the page) – so I rolled my own.

To use:

  1. add the class “rollover” to each anchor containing a rollover image
  2. name your rollover images the same as the original image, with the suffix “_on”, and place them in the same location as the original image
  3. finally, add the following to your onReady function:
// Preload
var rolloverImages = $('.rollover');
for(var i = 0; i < rolloverImages.length; i++){
  var pic = new Image(1,1);
  pic.src = $('img', rolloverImages[i]).attr("src").split(".").join("_on.");
}
// Add hover functions
$(".rollover").hover(function() {
  $('img', this).attr("src", $('img', this).attr("src").split(".").join("_on."));
}, function() {
  $('img', this).attr("src", $('img', this).attr("src").split("_on.").join("."));
});