I'm making a search tool where all employees of a company can find their names. these values ββare retrieved using json. (this includes a link to a image of the employee).
My question. Sometimes the link doesn't exists (wrong input from the other system due to automatic generation). If thats so i want to replace the image with a default one. How can i check if a image-link doesn't exists/is wrong?
for ( i = 0; i < totalResultsToShow; i++) {
//when the photoURL isn't given
if (searchResults[i].photoURL == "") {
searchResults[i].photoURL = imagesURL + "silhouette.jpg";
}
//when the photoURL doesn't exists
//do something??
HTMLContent += "<div class=resultTableRow id=" + i + " onclick=resultClicked(" + i + ");>";
HTMLContent += "<div class=resultTableItemImage><img width ='" + resultsImageWidth + "' src='" + searchResults[i].photoURL + "' class=stretchWidth /></div>";
HTMLContent += "<div class=resultTableItemUser><p>" + searchResults[i].user + "</p></div>"
HTMLContent += "<div class=resultTableItemUsername><p>" + searchResults[i].username + "</p></div>"
HTMLContent += "</div>"; "</div>";
}
//put results on screen
I think 1 solution is to put the code for the image in a try/catch block. But i personally dont like try/catch blocks.
[EDIT 1] I agree with you about checking for existence and undefined. Only the link does exists in the Results array. But its a corrupt link. Is there any way to check links before adding them to the html in Javascript?
[EDIT 2] The error im getting is: GET http://...... /---.jpg 404 (Not Found)
[SOLUTION] notice the onerror=this.src='"+imagesURL+"/silhouette.jpg'
HTMLContent += "<div class=resultTableItemImage><img width ='" + resultsImageWidth + "' src='" + searchResults[i].photoURL + "' class=stretchWidth onerror=this.src='"+imagesURL+"/silhouette.jpg' /></div>";
Thnx