user4513271
user4513271

Reputation:

How to have two fallback image placeholders

This works really well for filling a placeholder in place of an image that doesn't exist.

<img src="cantfind.jpg" onError="this.onerror=null;this.src='http://placehold.it/600x600?text=No Picture'">

What I was curious about is if there was a way to do two placeholders within the onError event. So I tried doing this but the Javascript isn't coming to me. any ideas? I tried assigning the urls to variable, but I'm not sure how to check for if the first placeholder fails without doing some messy xhr request or something.

Upvotes: 0

Views: 230

Answers (2)

ManoDestra
ManoDestra

Reputation: 6473

Here's one way of doing it via recursive event handling... try loading and if it errors, then try loading the first element from the array, and set it to error with the next index on failure, until you hit an index that is out of range, at which point stop.

This caters for any number of defined placeholders in the sources array.

<img id="img" src="example.jpg" onerror="loadNextImage(0);" alt="logo image">
<script>
var imagesDir = 'path/to/images/directory/';
var sources = [ '01.jpg', 'test.gif', 'bamf.jpg', 'foobar.jpg' ];
var index = 0;

function loadNextImage(index) {
    var image = document.getElementById('img');
    if (index < sources.length) {
        console.log('Index:', index, sources[index]);
        image.onerror = function() { loadNextImage(index + 1); };
        image.src = imagesDir + sources[index];
    } else {
        image.alt = 'No suitable image found to display';
    }
}
</script>

Upvotes: 1

woxxom
woxxom

Reputation: 73526

Check if the current src equals one of the placeholders and assign a new url accordingly:

onerror="
    var p1='http://.......', p2='http://......'; 
    if (this.src == p1) this.src = p2; else if (this.src != p2) this.src = p1;
"

Upvotes: 1

Related Questions