Search code examples
javascriptjqueryimageondemand

How to load image on demand


I have this simple image zoom jQuery. Here is a Demo example. It uses the elevateZoom jQuery.

The code behind is very simple:

<img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/>
<script>
   $vc("#zoom_05").elevateZoom({
  zoomType              : "inner",
  cursor: "crosshair"
});
</script>

My question, is how can i make the large image load on demand, only when the mouse is over it. Please have a look at this demo example and let me know what i need to add in the code.


Solution

  • img element (id="zoom_05") above, would not load large_image1.jpg on its own. Large image load happens because elevateZoom() looks into its data-zoom-image value and immediately loads it. One way around this behaviour is to defer elevateZoom() until user hover's over the small image for the first time. Quick example:

       jQuery( function () {
    
       var elevate_zoom_attached = false, $zoom_05 = $("#zoom_05") ;
    
        $zoom_05.hover(
         // hover IN
         function () {
            if ( ! elevate_zoom_attached ) {
            $zoom_05.elevateZoom({
                      zoomType : "inner",
                      cursor   : "crosshair"
                    });
            elevate_zoom_attached = true ;
            };
        },
         // hover OUT
         function () {
            if ( elevate_zoom_attached) { // no need for hover any more
              $zoom_05.off("hover");
            }
         }
      );
    
    }) ;
    

    Mind you this is an quick, on-top-of-my-head code, but should work ... Also in this case elevateZoom() action might not be immediate while large image loading is going on.