Search code examples
javascriptonerror

Replace broken img with fallback picture


It's really simple: if the link to a pic is broken a backup link steps in. I've googled this and it should be straight forward but I can't get it working. I need to add it in Javascript and this is the line I've been trying to fix it with:

var issuePicFront = document.createElement("img");
issuePicFront.id = "first" + count;
issuePicFront.src = issues[count].images.imageFront;
issuePicFront.onerror="this.src=replacePic";
var replacePic = https://www.jordans.com/~/media/jordans%20redesign/no-image-found.ashx?h=275&la=en&w=275&hash=F87BC23F17E37D57E2A0B1CC6E2E3EEE312AAD5B

I still get 404 (Not found). According to the majority och the internetz this is the common solution but don't work for me.

Any clues to solve this?


Solution

  • You should put quotes around the fallback URL (Assuming the rest of the code is working).

    I would also suggest to change the error handler to a function, like this:

    issuePicFront.onerror=function(e){
       var replacePic = '<URL>'
       this.src=replacePic;
    };