In some web sites, ebay and Amazon specifically, they have several thumbnails below a larger image. When you hover over one of the thumbnails the corresponding larger image is displayed in the space above.

This effect would be perfect for a site that I am working on right now. Can anybody show me how they do this?

Many TIA!
Dennis

Dani AI

Generated

— this is the common thumbnail-to-main-image swap pattern. was right that JavaScript is the right tool; the usual, accessible pattern is to store each large-image URL on the thumbnail (via a data- attribute), swap the main <img> src on mouseover and on keyboard focus, and use event delegation so you do not need a listener per thumbnail.

A minimal HTML structure:

<div class="product-gallery">
  <img id="mainImage" src="images/large1.jpg" alt="Product view 1" width="600" height="400">
  <ul id="thumbs">
    <li><img src="images/thumb1.jpg" data-large="images/large1.jpg" alt="View 1"></li>
    <li><img src="images/thumb2.jpg" data-large="images/large2.jpg" alt="View 2"></li>
    <li><img src="images/thumb3.jpg" data-large="images/large3.jpg" alt="View 3"></li>
  </ul>
</div>

Vanilla JS (event delegation + keyboard support + optional preloading):

(function(){
  var main = document.getElementById('mainImage');
  var thumbs = document.getElementById('thumbs');

  function showLarge(img){
    if (img && img.dataset && img.dataset.large) main.src = img.dataset.large;
  }

  thumbs.addEventListener('mouseover', function(e){
    showLarge(e.target);
  }, false);

  thumbs.addEventListener('focusin', function(e){
    showLarge(e.target);
  }, false);

  // optional preload (beware of too many/huge images)
  Array.prototype.slice.call(thumbs.querySelectorAll('img')).forEach(function(t){
    if (t.dataset && t.dataset.large) new Image().src = t.dataset.large;
  });
})();

Notes and tips: give the main image fixed width/height or a css aspect-box to avoid layout shift; use focusin/keydown so keyboard users can change views; prefer pointerenter/pointerleave or mouseover depending on how granular you want the events; avoid preloading dozens of multi-MB images — instead preload nearby thumbnails or lazy-load on first hover. For no-JS fallback, wrap thumbnails or the main image in links to the large file so the gallery is still usable with JavaScript off.

Recommended Answers

All 2 Replies

There are many implementations & approaches to achieve what you want, but most of them will require JavaScript (please don't use flash for this). One way to do is to load all your images in thumbnails and change the image display URL to the image your mouse is over. You should ask this question in JavaScript/DHTML/Ajax forum.

Thanks! Reposted as suggested.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.