Pre-loading Images and Creating MouseOver Effects in JavaScript by Scott Clark and Ronnie Moore First published: January, 1999 We show you how to do it, and even do it for you using our nifty script generator! Some of the most common questions we're called upon to answer from our readers are "How can I preload some images for use in a mouseover effect?" and "How can I make an image change when the mouse is moved over it?" In this tutorial, we're going to show you how to perform both tasks, and we're even going to provide you with a Preload/Rollover Script Generator, created especially for our readers. To get started, check out our Preload - Rollover Script Generator. Fill in the empty form fields, three for each preload/rollover effect you wish to use. The first field is for the initial image which will be shown on your page. You can use a relative URL for the image, such as alien1.gif, or you can use the full URL, like http://webdeveloper.com/javascript/alien1.gif. The second field is where you'll place the URL for the rollover image--the one that will be pre-loaded. Again, you can use a relative or a full URL. The third blank is where you'll place the URL for the hyperlink itself, such as http://www.webdeveloper.com. Continue in this fashion until you have listed all the images you wish to use as mouseovers (you can create five pre-loads/mouseovers using the generator), and then click the button on the bottom of the page. The JavaScript code for your pre-load and your mouseover effects will be generated in the large form field at the bottom on the page. Now you'll want to cut and paste the code into your own HTML page. Place the script itself in the HEAD of your document, and then place the mouseover code where you want it to appear in the BODY of your document. The generator automatically creates the HEAD and BODY tags, but these are mostly so you'll get a better idea of where each section goes. Here's the way it works: As the page is loading the initial images, it also pre-loads the mouseover images. As the mouse is moved over the initial image, the script changes the source for the image to the (new) mouseover image. When the mouse is moved off the image, the script changes the source back to the original image. Simple, yet elegant! This works for and with both Netscape and MSIE browsers, so have phun! |