Question

I have an img element:

var photo = document.createElement("img"); 

which is feed by photos with name stored in an array of objects, so I "feed" the photos like this:

photo.setAttribute('src', './pics/' + myarray[id].Name + '.jpg');

And it works perfect.

The only thing not working is to set an attribute with a default photo for the element that don't have a pic.

I have tried to do a setAttribute line above that one, setting a "default" picture for all the elements, hoping that the second line would replace with proper picture the elements that have one, and leave the default ones untouched, but no... console.log still showed a message of expecting a name+jpg scheme, it totally ignored my previous line (so I am pretty sure is not how it works).

So if you have an img element with many instances through an array, what is the best way to assign a default picture to the elements whose picture is not specified in purpose?

Thanks!

Was it helpful?

Solution

Can you use jQuery. This is a solution for the problem you described. If an image comes back as a 404 then it gets the default image applied

http://jsfiddle.net/gunderson/D3DSt/

var photo = document.createElement("img");
photo.setAttribute("id", "myPhoto");
$('body').append(photo);

$("#myPhoto").attr("src", 'alogo3w.png').error(function() {
    $(this).attr("src", "https://www.google.com/images/srpr/logo3w.png");
  })
​

OTHER TIPS

Just set only the default if neccessary

photo.setAttribute('src', './pics/' + ( myarray[id].Name ? myarray[id].Name : 'default' ) + '.jpg');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top