Search code examples
svghoverpngfallback

SVG hovers with fallbacks


What is the bestpractice, when I need to have SVG images with SVG hovers with fallbacks?

I mean SVG images with PNG fallbacks (normal, reaponsive 2x, 3x), and change them on hover to other SVG images with PNG fallbacks?

Is it better to use <img /> or <picture> + <source /> + <img /> tag with jQuery (or vanilla, but I already use jQuery), or to have it all in CSS as backgrounds? If jQuery, does it mean swapping srcsets? If CSS, how do I best include @2x and @3x image versions?

Also, how does the used method affect preloading of the hovers? It would surely be much better without blinking.

So far I have this, I need to change them on hover to 1hov.svg, 1hov.png, 1hov@2x.png, 1hov@3x.png

<a href="#">
 <picture>
  <source type="image/svg+xml" srcset="logos/1.svg">
  <img src="logos/1.png" srcset="logos/1@2x.png 2x, logos/1@3x.png 3x" alt="logo">
 </picture>
</a>

Solution

  • Here is a HTML + jQuery solution I found. It swaps the src and sourcesets to their hover alternatives. Includes the hovers preloading.

    HTML

            <a href="#" target="_blank">
                <picture>
                    <source type="image/svg+xml" srcset="logos/1.svg" data-swap-srcset="logos/1hov.svg">
                    <img src="logos/1.png"  data-swap-src="logos/1hov.png"
    srcset="logos/1@2x.png 2x, logos/1@3x.png 3x" data-swap-srcset="logos/1hov@2x.png 2x, logos/1hov@3x.png 3x" alt="logo">
                </picture>
            </a>
    

    jQuery

    //preload hovers
    $("source[data-swap-src]").each(function(){
        $('<img/>')[0].src = $(this).attr("data-swap-src");
    });
    $("img[data-swap-src]").each(function(){
        $('<img/>')[0].src = $(this).attr("data-swap-src");
        $('<img/>')[0].srcset = $(this).attr("data-swap-srcset");
    });
    
    $("a").hover(function(){
       var newone = $(this).find("img").attr("data-swap-src");
       $(this).find("img").attr("data-swap-src", $(this).find("img").attr("src"));
       $(this).find("img").attr("src", newone);
       newone = $(this).find("img").attr("data-swap-srcset");
       $(this).find("img").attr("data-swap-srcset", $(this).find("img").attr("srcset"));
       $(this).find("img").attr("srcset", newone);
       newone = $(this).find("source").attr("data-swap-srcset");
       $(this).find("source").attr("data-swap-srcset", $(this).find("source").attr("srcset"));
       $(this).find("source").attr("srcset", newone);
     }
    );