Search code examples
javascriptimage-preloader

Reference loaded <img> in javascript


I use a carousel jQuery plugin which defines a container which must contain <img> tags. The images are loaded and shown, the carousel works.

I am now implementing image preview on hover. I've created a separate <div> for this purpose which is being shown with the loaded image.

The problem is that I'm programatically creating a new <img> tag within the <div> each time the mouse hovers over a different image. This results in massive amount of unnecessary server requests.

How can I use preloaded images from the carousel within the image preview div?

I don't need a fully working solution, I'll accept abstract answers.


Solution

  • Further to the comments, here's a working sample of the cloneNode method I mentioned. I've not bothered with the mechanics of the containers or of triggering the behaviour via a mouse hover, just click the existing image and it will work. You'll also have to change the image source to something you already have. I'm testing with the full-res version of this image: https://commons.wikimedia.org/wiki/File:SoundingRocketSamplePayload-02.jpg

    <!DOCTYPE html>
    <html>
    <head>
    <script>
    "use strict";
    function byId(id,parent){return (parent == undefined ? document : parent).getElementById(id);}
    
    window.addEventListener('load', onDocLoaded, false);
    function onDocLoaded()
    {
        byId('srcImg').addEventListener('click', myTest, false);
    }
    
    function myTest()
    {
        var tgtElem = byId('srcImg');
    
        var clone1 = tgtElem.cloneNode(true);
        var clone2 = tgtElem.cloneNode(true);
        var clone3 = tgtElem.cloneNode(true);
    
        document.body.appendChild(clone1);
        document.body.appendChild(clone2);
        document.body.appendChild(clone3);
    }
    </script>
    <style>
    </style>
    </head>
    <body>
        <img id='srcImg' style='width: 256px' src='rockets.jpg'/>
    </body>
    </html>