By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,299 Members | 1,247 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,299 IT Pros & Developers. It's quick & easy.

Javascript to change image depending on time..

P: 3
Hi there,

Basically, I've got a script which changes the page background depending on the time.

Expand|Select|Wrap|Line Numbers
  1. <script language="JavaScript">
  2.     day=new Date()     //..get the date
  3.     x=day.getHours()    //..get the hour
  5.     if(x>=0 && x<4) {
  7.        document.write('<style type="text/css">#header{background: white url(images/assets/1st.jpg); color: black}"></style>')
  9.     } else
  11.     if(x>=4 && x<12) {
  13.        document.write('<style type="text/css">#header{background: white url(images/assets/2nd.jpg); color: black}"></style>')
  15.     } else
  17.     if(x>=12 && x<18) {
  19.        document.write('<style type="text/css">#header{background: white url(images/assets/3rd.jpg); color: black}"></style>')
  21.     } else
  23.     if (x>=18 && x<24) {
  25.        document.write('<style type="text/css">#header{background: white url(images/assets/4th.jpg); color: black}"></style>')
  27.     }
  28. </script>
So as you can see, the first background changes between at 4am and so on.

What I would look to do is to change the background at different times every day, reading from some sort of text file or something. For example, on the 10th June the first background changes at 4:15am and the others with different times, on the 11th June the first background changes at 4:22am or something and so on.

Could someone possibly find me or write me something to do this? I can't find anything anywhere!

Thanks ever so much
Jul 6 '11 #1
Share this Question
Share on Google+
4 Replies

Expert Mod 10K+
P: 12,430
Just so you know, your current script can be simplified to
Expand|Select|Wrap|Line Numbers
  1. day=new Date() //..get the date
  2. x=day.getHours() //..get the hour
  4. document.write('<style type="text/css">#header{background: white url(images/assets/' + Math.floor(x/4) + '.jpg); color: black}"></style>')
As for your question, you will have to hard code it in to your javascript unless you plan on using server side scripting.
Jul 6 '11 #2

P: 3
Thanks for the simplification.
Yeah I think I'd go for with hard coding it into the JS as it'd be easier.
Jul 6 '11 #3

Expert Mod 10K+
P: 12,430
Just a quick note but for the simplification, you'll have to rename the image files 1, 2, 3, and 4. Not 1st, 2nd, 3rd, 4th.
Jul 6 '11 #4

P: 3
Managed to sort it :) For reference if anyone else wants such functionality:

Thanks for the help though Rabbit
Jul 7 '11 #5

Post your reply

Sign in to post your reply or Sign up for a free account.