Search code examples
javascriptjquerysliderthumbnailsjquery-load

How to check if image url has been loaded with jQuery?


I have this code here where I have a slider with thumbnails and the sliders large image takes it's next attr('src') from the click on a thumb, but I'd like to change that src only when the image has loaded. This is the source that I've come up with so far:

$('.thumb').click(function(){
    topImageSrc = $(this).data("bigimage");

    $(topImageSrc).load(function(){
        coverMain.attr('src',topImageSrc);
        main.fadeOut("slow");
    })
});

Sadly this doesn't work as the topImageSrc is just a path variable to the large image, like so: /uploads/largeimages/pic1.jpg

How could I force it to load and then check if it's done, after that - apply the new image?


Solution

  • You can do it like this:

    $('.thumb').click(function () {
        topImageSrc = $(this).data("bigimage");
        var topImage = $('<img>').attr('src', topImageSrc);
        $(topImage).load(function () {
            coverMain.attr('src', topImageSrc);
            main.fadeOut("slow");
        });
    });
    

    This creates an image (without appending it anywhere), sets its source to the topImageSrc URL and checks for the load event.