I have a <picture>
element with 2 images. An .avif
image and a .jpg
fallback.
<picture id="mouse-event" onm ouseover="this.src='/animated.webp'">
<source type="image/avif" srcset="/sm.avif">
<img src="/sm.jpg">
</picture>
When I move my mouse over the <picture>
element, I want to replace the the shown image with an animated .webp
(smiliar to youtube thumbnail hover).
I have tried putting onmouseover
on the picture element but that didn't work.
Also I tried replacing the src with javascript without success:
document.getElementById("mouse-event").src = "/animated.webp";
(Just for fun I added the onm ouseover event to the img tag. That works, but only if I disable browser support for .avif so that the jpg is shown.)
How can I achieve an image replacement onm ouseover with a picture element so that avif/jpg fallback is still possible?
CodePudding user response:
You need to replace the img
element's src
or the source
element's srcset
, not the picture
element's src
.
For example
<picture id="mouse-event" onm ouseover="doMouseover">
<source type="image/avif" srcset="/sm.avif">
<img id='theImage' src="/sm.jpg">
</picture>
<script>
doMouseover() {
document.getElementById('theImage').src ='/animated.webp'
}
</script>