Erica Knight Erica Knight -4 years ago 97
Javascript Question

Fill parent div with the image being hovered over

I am still fairly new to JS, and I am trying to replace the HTML of a div with a picture that is being moused over, and when the mouse leaves I want it to return to it's normal state. I thought that I did everything right but my code doesn't seem to be working. I've looked through stack overflow and I see a lot of jQuery solutions to my 'problem,' but I would like an answer in pure JavaScript (I'm trying to "maser" this first), along with an explanation so I can understand why the answer IS the answer. Thanks.

I'll try to explain myself (my code). I grabbed reference to the image holder, and I grabbed reference to the the images. I thought I made a function that looped through the array of images and added an event listener to whichever image ( image[i] ) was being moused over. Then, I added an event listener that is supposed to return the image holder to it's default state by inserting the original HTML. I just don't understand how to fix this.

var holder = document.getElementById('holder');
var images = document.getElementsByTagName('img');

var popImage = function () {
for (i = 0; i < images.length; i++) {
images[i].addEventListener('mouseover', = function () {
holder.innerHTML = images[i];
images[i].addEventListener('mouseout', function () {
holder.innerHTML =
'<div class='col-md-3 img-fluid' id='img1'><img src='photo1.jpg'></div>
<div class='col-md-3 img-fluid' id='img2'><img src='photo2.jpg'></div>
<div class='col-md-3 img-fluid' id='img3'><img src='photo3.2.jpg'></div>
<div class='col-md-3 img-fluid' id='img4'><img src='photo4.jpg'></div>'


Answer Source

You said you are new to JS and just learning which is great but an important part of learning JS is learning when not to use it. As @Yoda said if this was for production you really should use CSS instead of JS.

Here is one way you could accomplish this with pure CSS

   .img {
      width: 100px;
      height: 100px;
      background: #bada55;
      border: 2px solid #333;
      float: left;
   .holder:hover > .img {
      opacity: 0;
   .holder:hover > .img:hover {
      opacity: 1;

<div class="holder">
  <!-- Using div.img for simplicity, these whould be your <img/> tags -->
  <div class="img">1</div>
  <div class="img">2</div>
  <div class="img">3</div>
  <div class="img">4</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download