Cheluis
Cheluis

Reputation: 1412

Way to implement a callback into a .attr in jquery

I'm working with canvas and images. In certain point of my flow, I have to set the src attribute of a image:

$("#image").attr("src", "something");

And then I do some processing that implies messing up with the image. But if I don't put an alert() between the .attr() and the call of the next line, it doesn't work. With the alert it works just fine. I had to call a setTimeout() in order to give some time to the .attr() to finish.

$().load doesn't work because the image is loaded, the src of the image is changed with a click. So, is there a way to implement a callback in .attr()? If there is not such way, which could be the better way to accomplish this?

Thanks in advance

Upvotes: 1

Views: 148

Answers (2)

jValdron
jValdron

Reputation: 3418

Try using a preloading technique:

var imagePreloader = $("<img />").attr("src", "something");
imagePreloader.bind('load', function(){

    // image has been loaded in your browser cache, now you can
    // change the source of your real image
    $("#image").prop("src", "something");

});

Upvotes: 3

troelskn
troelskn

Reputation: 117467

Could you replace the image with a new image, rather than changing its source?

Upvotes: 0

Related Questions