kahuna
kahuna

Reputation: 49

Showing alternative image if img src is not working properly

I'm working on a web page and I have this function which is showing the pic of the day of a parent site

function LoadPage() { 

var today = new Date(); 

var yyyy = today.getFullYear(); 

var mm = today.getMonth()+ 1; 

var dd = today.getDate(); 

var url="http://myparentsite"+yyyymmdd+"/image.jpg";
document.getElementById("img").setAttribute("src",url);

}

The pic of the day is usually set in the morning so I've a problem between midnight and 7-8 am during those hours the browser will show the "?" of "image not found". How can I set it to show the image of the day before? I tried

var dd2 = today.getDate() -1; 

var url2="http://myparentsite"+yyyymmdd2+"/image.jpg";

but I don't know how to handle it in the function and in the Html.

Upvotes: 1

Views: 3949

Answers (3)

Arpit Aggarwal
Arpit Aggarwal

Reputation: 29276

Try This:

    <img src="http://myparentsite/imageOfTheDay.jpg" alt="" onerror="this.src='http://myparentsite/alternateImageOfTheDay.jpg'"/>

-Arpit

Upvotes: 0

SoWeLie
SoWeLie

Reputation: 1391

Basically, you need to handle an event on the image.

document.getElementById("img").onError = function() {
    // the image didn't load properly, change the src attribute
    document.getElementById("img").setAttribute("src", url2);
}

document.getElementById("img").setAttribute("src",url);

Upvotes: 0

Chad Brown
Chad Brown

Reputation: 1667

Simple answer is have the parent site reference a constant image location, when you have a new daily image then overwrite the image with the new one and archive the old daily image.

<img src='http://myparentsite/imageOfTheDay.jpg'/>

otherwise you can check for an error and set it to yesterday's image

document.getElementById("img").onError = function() {
   var dd2 = today.getDate() -1; 

   var url2="http://myparentsite"+yyyymmdd2+"/image.jpg";

   document.getElementById("img").setAttribute("src",url2);
}

or check the date of the request and determine what image to show

 var now = new Date();
 var now_utc_hour = now.getUTCHours();

 url = "http://myparentsite"+yyyymmdd+"/image.jpg";

 if( now_utc_hour > 7 && now_utc_hour < 8 ) "http://myparentsite"+yyyymmdd2+"/image.jpg";

 document.getElementById("img").setAttribute("src",url);

Upvotes: 1

Related Questions