Search code examples
htmlimagerolloversrcset

Simple rollover effect using picture source srcset with next-gen images like .webp


Updating code and optimizing site speed so trying to change this simple html rollover effect:

<img src="img1.jpg" onmouseover="this.src='img2.jpg'" onmouseout="this.src='img1.jpg'">

To something along the lines of this:

<picture>
<source srcset="img1.webp" type="image/webp" onmouseover="this.src='img2.webp'" onmouseout="this.src='img1.webp'">
<source srcset="img1.jpg" type="image/jpeg"  onmouseover="this.src='img2.jpg'" onmouseout="this.src='img1.jpg'">
<img src="img1.jpg" onmouseover="this.src='img2.jpg'" onmouseout="this.src='img1.jpg'">
</picture>

I didn't really expect the latter to work, but am mentally blocked as to the correct approach for this basic effect so the browser will access the appropriate image format.


Solution

  • Assuming one is already using Modernizr js, here is one possible solution using CSS & HTML:

    .webp .rollover{
      background:url("/img3/img1.webp")
      }
      
    .webp .rollover:hover{
      background:url("/img3/img2.webp")
      }
      
    .no-webp .rollover{
      background:url("/img3/img1.jpg")
      }
      
    .no-webp .rollover:hover{
      background:url("/img3/img2.jpg")
      }
    <div class="rollover"></div>

    I know there are other solutions as well, but this one worked for me.

    One downside of this approach is there is a lag while img2.xxx is loaded 'onHover'. However, this also means img2 is not explicitly 'preloaded', hence speeding up overall page download time. (One could finesse this too).