1

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.

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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);

2 Comments

I tried this but maybe I'm missing some code.Where should I call the url2 to show the alternative image?
Edited my answer to include where you should include your second URL.
0

Try This:

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

-Arpit

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.