Nice image swapping

Here’s a nice, clean, and simply way to swap an image on a click of a link. You might use this if you have one large image a series of thumbnails, and when you click on the thumbnail you want to swap the large image.

This javascript will do that and you don’t even need any additional libraries!


It works by having an extra property in the html tags called ‘show’. This will tell the javascript what image you want to show when the link is clicked on. You also have an image with the id ‘swap’ so that the javascript knows what is the image to be replaced.

The javascript looks like this:

<script type="text/javascript">
   simg = {
       init: function() {
           if (document.getElementById) {
               allAnchors = document.getElementsByTagName('a');
               if (allAnchors.length) {
                   for (var i = 0; i < allAnchors.length; i++) {
                       if (allAnchors&#91;i&#93;.getAttributeNode('show') && allAnchors&#91;i&#93;.getAttributeNode('show').value != '') {
                           allAnchors&#91;i&#93;.onclick = simg.showImage;
                       }
                   }
               }
           }
       },
       showImage: function() {
           var mainImage = document.getElementById('swap');
           mainImage.src = this.getAttributeNode('show').value;
           return false;
       },
       addEvent: function(element, eventType, doFunction, useCapture) {
           if (element.addEventListener) {
               element.addEventListener(eventType, doFunction, useCapture);
               return true;
           } else if (element.attachEvent) {
               var r = element.attachEvent('on' + eventType, doFunction);
               return r;
           } else {
               element&#91;'on' + eventType&#93; = doFunction;
           }
       }
   }
   simg.addEvent(window, 'load', simg.init, false);
</script>

What you’ll want to do is set your links to whatever page or script you would normally use if you didn’t have javascript image swapping. That way if people don’t have javascript or an old browser then they will still get a functioning site.

Some example HTML:

<html>
<head>
    <script type="text/javascript" src="swap.js"></script>
</head>
<body>

<img src="default.jpg" id="swap" style="margin-bottom:2em;" />
<a href="index.php?file=img1.jpg" show="img1.jpg"><img src="img1_thumb.jpg" />
<a href="index.php?file=img2.jpg" show="img2.jpg"><img src="img2_thumb.jpg" />
<a href="index.php?file=img2.jpg" show="img3.jpg"><img src="img3_thumb.jpg" />

</body>
</html>

Nice a clean, but with image swapping and no additional libraries! Nice.

Did you like this? Share it:

Leave a Reply