0

I have the following code that is bugging me : Fiddle

These are the desired behaviours:

  • If the image does not exist, I want to load another image changing the src attribute
  • If that image also fails loading, the image should be hidden.
  • If the image successfully loads (exists), I want it to be shown

HTML

<div id="test">
    <img id="myimage" src="nonono.jpg" />
</div>

JS

$("#test img").error(function () {
    console.log("error loading img " + $(this).attr("src"));
    $("#myimage").attr("src", "yuyuyu.jpg")
}).load(function () {
    console.log("success loading img " + $(this).attr("src"));
})

//--- Simulate a new image load
$("#myimage").attr("src", "yeyeye.jpg");

This is what the console output loosk like:

GET http://fiddle.jshell.net/_display/yeyeye.jpg 404 (Not Found)

error loading img yeyeye.jpg (index):23

success loading img yuyuyu.jpg (index):26

GET http://fiddle.jshell.net/_display/yuyuyu.jpg 404 (Not Found)

isn't it weird? both images does not exist, I'm expecting two times the error message, but I get a SUCCESS instead!

any idea? Am I missing something?

Thank you


UPDATE

I've tried to add a setTimeout to the src attribute change, to better understand which images does fire the load event.. and.. the load event is not fired!

see fiddle here: Fiddle with timeout

JS

$("#test img").error(function(){
    console.log("error loading img " + $(this).attr("src"));
    setTimeout(function(){
             $("#myimage").attr("src", "yuyuyu.jpg")
    }, 1000)
}).load(function(){
    console.log("success loading img " + $(this).attr("src"));  
})

Why?

1 Answer 1

1

This is not weird, the function runs on Complete not Success so even an error is a completed request. See jQuery load documentation.

If you load an image like this, you can access the status of the request.

$("#test img").load("yuyuyu.jpg", function(response, status, xhr) {
    alert(status); 
});

You can get the specific error code via: xhr.status
You can also get a textual representation of the error via: xhr.statusText

See fiddle. Also see another example.

2
  • I totally missed that, thank you. What if I want to handle both the errors (from the 1st and the replacement image)? any suggestions?
    – BeNdErR
    Jan 28, 2014 at 14:44
  • @BeNdErR since it's an onload event on the html element itself, you changing the src attribute doesn't change the fact that the load event will be fired a second time once the second image is loaded. It should work fine without amendments. You would have to detect if it is the second load, and then tell it to be removed though. Jul 24, 2018 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.