2

I'm using this code to build a gallery:

        window.onload=function(){
        var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
        var mainImage = document.getElementById('rr_lrg_img'); 

        [].forEach.call(image,function(x){ 
            x.onmouseover = function(){
                 mainImage.src = x.src; 
             };
        });
        }

The code loads different thumbnails on the big image when "onmouseover". Now I would like to "preload" the first image from that gallery of thumbnails. I tried using onload with

rr_lrg_img.src=document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img')[0].src

but then it conflicts with the onmouseover. Any ideas? I can only use javascript, no jquery.

Rose
  • 23
  • 4

1 Answers1

1

Since your var image is actually a collection of images, you need to use the [0] index pointer to target the first one:

window.onload=function(){
  
  var image = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('img');
  var mainImage = document.getElementById('rr_lrg_img'); 
  
  mainImage.src = image[0].src; // Add this line (preload first image into main one)
  
  function toMainImage() {
     mainImage.src = this.src; 
  }

  [].forEach.call(image,function(x){
    x.addEventListener("mouseenter", toMainImage, false);
  });
  
}
.thumbnails img{height:50px;}
<img src="//placehold.it/200x200&text=default" id="rr_lrg_img">

<div class="thumbnails">
  <img src="//placehold.it/200x200/cf5&text=1">
  <img src="//placehold.it/200x200/f0f&text=2">
  <img src="//placehold.it/200x200/444&text=3">
</div>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • Thanks @Roko C. Buljan, great answer! Wish I could offer you a beer. Since I'm very new to javascript and I know next to nothing about best practices, I also need to "void" the hrefs on the anchors, like `var anchor = document.getElementsByClassName('thumbnails')[0].getElementsByTagName('a'); anchor.href = '#';` Where and how would you put that in the code? – Rose Jan 18 '15 at 12:22
  • @Rose why would you set the href to `#`? In your question you're asking hot to change the `src` of an element. If you're 100% sure that you cannot find here on SO a question about how to change an anchor HREF, please ask a new question. – Roko C. Buljan Jan 18 '15 at 12:35
  • No worries, I just figured it out :) I needed to set them to # to make the gallery compatible with mobile screens (tap). Thanks again for your main answer, it really helped. – Rose Jan 18 '15 at 13:00