Search code examples
javascriptjqueryhtmlajaxxmlhttprequest

Is there a way to fade in and out the same image URL on loop with javascript?


I have an image stored on the webserver (example.com/webcam.jpg) that is updated server-side.

I would like to insert this image on a static HTML page but with a loop that keeps reloading the image (possibly fading from the previous to the current image)

There are jquery examples that fades between 2 images with 2 different addresses, but in my case, the image is always stored at the same URL and the loop/fade has to continue until the user leaves the page.

So far all I'm doing to keep it functional but not very pleasing, is using <meta http-equiv="refresh" content="5"> to refresh the whole page.


Solution

  • You can use setInterval to setup a loop.

    https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

    In the loop, set the image src= to your source image, but this will not refresh your image as it will be cached by the browser, so you need to add something to the URL so the browser thinks it's a new image.

    setInterval(function() {
        document.getElementById("myimage").src = "/myimage.jpg" + new Date().getTime();
    }, 5000);
    

    You can add a simple fadeIn/fadeOut

    setInterval(function() {
        $("#myimage").fadeOut(function() {
            this.src = "/myimage.jpg" + new Date().getTime();
            $(this).fadeIn();
        });
    }, 5000);
    

    It would be better to wait for the image to finish loading, see this answer: https://stackoverflow.com/a/5789300/2181514

    For an even smoother effect, you could use two images like the answers you already found then there would be no need to hide one while the other is loading. Place them on top of each other using position:relative / position:absolute then fadeIn one while fadeOut the other to get them to transition (but not really part of this question, just to improve the UX).