Search code examples
javascriptmouseentermouseleave

Trying to add a mouseenter and mouseleave function to an image


I am trying to add a mouseenter and mouseleave function to an image. I want the src of the image to change when the mouseenter occurs and to change back when the mouseleave occurs. The src of the image right now is currently changing in the dom but the image does not change. There is a srcset attribute on the image as well which I have tried changing on the mouseenter but I just get a blank white background. Here's the code I have:

document.addEventListener("DOMContentLoaded", function () {
  const img = document.querySelector("#div1 img");

  img.addEventListener("mouseenter", function () {
    img.src = "https://images.unsplash.com/photo-1542826045-6a629cdc8b1f?ixlib=rb-1.2.1&auto=format&fit=crop&w=1389&q=80";
    img.setAttribute('srcset', 'https://images.unsplash.com/photo-1542826045-6a629cdc8b1f?ixlib=rb-1.2.1&auto=format&fit=crop&w=1389&q=80')
  })

  img.addEventListener("mouseleave", function () {
    img.src = "https://images.unsplash.com/photo-1598104514968-1bb2c80c5994?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=675&q=80";
    img.setAttribute('srcset', 'https://images.unsplash.com/photo-1598104514968-1bb2c80c5994?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=675&q=80');
  })
})

Solution

  • Adding it here instead of comments because the suggestion is a bit lengthy.

    Your image path is not fetching any image. I tried out with some other valid image and it worked. See the snippet below

    img{
     height: 200px;
    
    }
    <div id="div1">
      <img src="https://images.unsplash.com/photo-1598382569639-d28c1a9a21da?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80" />
    </div>
    
    <script>
    
    document.addEventListener("DOMContentLoaded", function () {
      const img = document.querySelector("#div1 img");
    
      img.addEventListener("mouseenter", function () {
        img.src = "https://images.unsplash.com/photo-1598557334954-f501396943e7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80";
        
      })
    
      img.addEventListener("mouseleave", function () {
        img.src = "https://images.unsplash.com/photo-1598382569639-d28c1a9a21da?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=934&q=80g";
       
      })
    })
    </script>