Strontium_99
Strontium_99

Reputation: 1803

jQuery .error event

I know this is such a lame question to ask, but it seems like I'm having trouble getting my brain back in gear after the Christmas period.

Simple question, I'm using the jQuery .error event to replace broken images using this bit of script

    $('#slideshowContainer img[name=imgStockItem]').error(function(){
         $(this).attr('src', '/assets/images/no-image-large.png');
    });

What I really want to do is have something like an if/else deal, where if the image is broken do this, else, do this.

I tried this:

   if($('#slideshowContainer img[name=imgStockItem]').error()){
          alert("true");
   } else {
          alert("false");
   }

But that just returns a true everytime, broken image or not.

Any ideas please?

Upvotes: 0

Views: 795

Answers (2)

Shadow Wizard
Shadow Wizard

Reputation: 66399

The .error() event means.. error.

To know if image was loaded successfully, handle the .load event.

Now comes the tricky part.. to have jQuery (or JavaScript in general) trigger any of those events, you'll have to manually assign the image src otherwise it will be "too late".

So, have such image tag:

<img name="imgStockItem" my_src="image_source_here.png" />

Then such code:

$(document).ready(function() {
    $('#slideshowContainer img[name=imgStockItem]').each(function(index) {
        $(this).error(function() {
            $(this).attr('src', '/assets/images/no-image-large.png');
            $("#StatusDiv").append("image #" + (index + 1) + " is broken<br />");
         });

        $(this).load(function() {
            $("#StatusDiv").append("image #" + (index + 1) + " loaded successfully<br />");
        });

        $(this).prop("src", $(this).attr("my_src"));
    });
});

StatusDiv is just example for container showing the status of each image.

Live test case.

Upvotes: 1

nav
nav

Reputation: 3115

Im going to make an assumption here but i think this maybe your problem

The event handler must be attached before the browser fires the error event, which is why the example sets the src attribute after attaching the handler.

See http://api.jquery.com/error/

You will have to attach the event when the src is set as once the browser renders the element it will make the request to the defined source, your problem is that it has thrown the error and you haven't caught it because the handler wasn't applied at that point.

You could try this (place before all your image markup):

$('#slideshowContainer').on({
    error: function() {
        $(this).attr('src', '/assets/images/no-image-large.png');
    }, 
    load: function() {
        // loaded successfully
    }
}, 'img[name=imgStockItem]');

Upvotes: 1

Related Questions