4

Possible Duplicate:
Changing background based on time of day (using javascript)

I'm looking to create a site where the background rotates a bunch on files for different times of day. Is there any way I can tie maybe a bit of javascript to change the background at certain times based on the either the server or script clock?

I'm looking to have a day/afternoon/evening/night/dawn set of backgrounds that I want to cycle through.

Community
  • 1
  • 1
olliejudge
  • 77
  • 4
  • Someone else has already given a [solution](http://stackoverflow.com/questions/4358155/changing-background-based-on-time-of-day-using-javascript) to this. – Shef Jun 19 '11 at 10:14

3 Answers3

3

Using the code in this question, fetch the local time, and change the CSS of the element, which keeps the background.

Community
  • 1
  • 1
Herr
  • 2,725
  • 3
  • 30
  • 36
3

You could do something like this, and then just pass the i variable to the element background-image:

var d = new Date(),
    h = d.getHours(),
    i;

if (h < 6) i = "night.jpg";
else if (h < 9) i = "dawn.jpg";
else if (h < 15) i = "afternoon.jpg";
else if (h < 21) i = "day.jpg";
else i = "night.jpg";

document.body.style.background = "url("+i+")";

http://jsfiddle.net/niklasvh/UZG9z/

Niklas
  • 29,752
  • 5
  • 50
  • 71
2

Add this into the head of your HTML document:

<script type="text/javascript">
    (function(){
        var styles = ['night', 'dawn', 'afternoon', 'day', 'evening'];
        var currStyle = styles[Math.floor(styles.length * (new Date()).getHours() / 24)];
        document.documentElement.className += ' ' + currStyle;
    }());
</script>

Then in your CSS you can use something like this:

.night #myelement {
    background-image: url(myImage.jpg);
}
.day body {
    background-color: red;
}
Karolis
  • 9,396
  • 29
  • 38