Most image swap scripts require you to list every image that you want to load. This not only requires a lot of initial effort, but it makes future maintanence more difficult than it needs to be.

The image below uses a generic script that checks every image on the page when the document loads. If the filename matches a specific pattern, event handlers are added to the image that performs the swap.

Image swap demonstration

Normal, non-hover images have a -off suffix. For example, the image above is called demo-off.gif. The hover images use a -on suffix. This means that simply naming your images allows you to create a swap pair.

Do make sure that dom.js is loaded before image-swap.js. The former provides functions that enable the event handlers to be added to the images.

You should also be aware that this script will impose limitations on the use of <body onload="…"> and window.onload=…;.

The code in dom.js provides, to a limited extent, the ability to add multiple event listeners to browsers such as Internet Explorer that do not support the W3C DOM Events module. However, the way in which it works means that use of either of the aforementioned techniques may overwrite any listeners added using the script.

There are two solutions:

  1. Include image-swap.js after all occurances of window.onload=… and after the body opening tag (if you use the onload attribute).
  2. Replace occurances of window.onload = …; with dom.events.addEventListener(window, 'load', …); and <body onload="…"> with <script type"text/javascript"> dom.events.addEventListener(window, 'load', function() { … }); </script>
    </head>
    <body>