Search code examples
javascriptjqueryhtmlautoresizeaspect-ratio

Wait for image to re-load before animation


I have an application that loads a list of photos into an array then, one by one, displays these photos. It is, supposed to be, designed to hide the image outside of the window just to the right. Then the image should slide in from right to left until it hits the left window border. However, when loading the next image, if the image takes a while to load the old image slides in. Once the new image is loaded, it replaces the old image after the animation is complete.

<body>
    <img id="bg" class="clicky" alt=""></img>
more html...
</body>


function nextImage(){ // Load the next image and slide in from the right
    raterReset(); // Function to reset keyboard hotkeys
    loadImage(); // VBScript function to read the next image and make the filename
    $("#bg").finish();
    updateContainer(); // Function that obtains the window h/w and aspect ratio of image
    showStatus("Next Image Loaded: " + intPhotoCount + " of " + intFileCount);
    $("#bg").animate({left: "+="+winW}, 0,function(){
        $("#bg").attr("src",objOriginFile);
        $("#bg").animate({left: "-="+winW}, 1500);
    });
}

I have tried using:

$("#bg").attr("src",objOriginFile).load(function(){
    $("#bg").animate({left: "-="+winW}, 1500);
});

The first image works great, but then the second slides in like it is supposed to and proceeds to run the slide animation a second time and it disappears to the left out of the window. on the third image, the image is already too far right and is out of the window.

Here is a link to the actual HTA. This must be run on a windows box with IE 8+.

https://dl.dropboxusercontent.com/u/52558409/Photorater/Photorater.zip

Note: I know my code isn't the greatest and I may have done much in ways that it probably shouldn't be done. Please be gentle :)


Solution

  • Instead of loading the images separately, you can load them once and move to the left only their container.

    Let's suppose you have images having width set to 300px:

    CSS:

    #wrapper {
        display: block;
        width: 300px;
        overflow: hidden;
    }
    
    #images-container {
        display: block;
        width: 1200px; /* the width is calculated as NO_OF_IMAGES*IMAGE_WIDTH */
        position: relative;
    }
    
    #images-container img {
        display: inline-block;
    }
    

    HTML:

    <div id="wrapper">
        <div id="images-container">
            <img ... />
            <img ... />
            <img ... />
            <img ... />
        </div>
    </div> 
    

    JS: animate the #image-container by moving it to the left until all images were shown