1

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');
  })
})
2

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Simba. The raw html and js works correctly. I think it has something to do with the WP theme I am using.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.