2

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?

Xeen
  • 6,955
  • 16
  • 60
  • 111

1 Answers1

2

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.

  • I suppose this should work, but I get `Uncaught Error: Syntax error, unrecognized expression: /uploads/largeimages/pic1.jpg` – Xeen May 03 '15 at 17:24
  • Are you adding that URL directly? Seems like you're missing quotes* around the URL. –  May 03 '15 at 17:27