Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load image while hovering over the link text (CSS + Javascript)

I am using CSS to show an image on hover.

HTML Markup

 <a class="preview"  href="#"> Preview
 <img src="thumbnail_01.jpg" class="hide-image" />
 </a>

CSS

.hide-image {
     display: none;
     z-index: 100;
     position: absolute;
}
.preview:hover .hide-image {
     display: block
}

When the user hovers over the "preview" link, the image displays.

The code works. However, I have over 100 images and they all load at the same time! I would like them to load only when the user hovers over the link.

like image 863
Hugo Rodas Avatar asked Aug 04 '26 20:08

Hugo Rodas


1 Answers

Load image while hovering over the link text.

var alist = document.getElementsByClassName("preview");

for (var i = 0; i < alist.length; i++) {
  alist[i].addEventListener('mouseover', function(num) { 
    return function() {
      loadImg(alist[num]);
    }
  }(i), false);
}

function loadImg(x) {
  x.querySelector(".hide-image").src=x.getAttribute("data-my-img");
}
<a class="preview" href="#" data-my-img="https://www.colormango.com/tipsimg/javascript.jpg">preview JS
  <img class="hide-image" />
</a>
like image 57
Howard Wang Avatar answered Aug 06 '26 11:08

Howard Wang