j3-3ra
Last Updated: February 25, 2016
·
3.987K
· barnettjw
43ea08b4fc547e8a5da87c207bea2123

Time-based CSS Background using JavaScript

Use JavaScript to apply a CSS class to change the background image of a page based on the time of day of the user's browser.

$(document).ready(function(){
    var d = new Date();
    var n = d.getHours();
    if (n > 19 || n < 6)
  // If time is after 7PM or before 6AM, apply night theme to ‘body’
      document.body.className = "night";
    else if (n > 16 && n < 19)
      // If time is between 4PM – 7PM sunset theme to ‘body’
      document.body.className = "sunset";
    else
      // Else use ‘day’ theme
      document.body.className = "day";
});

Here's a working demo up on codepen.io

Say Thanks
Respond

3 Responses
Add your response

4839
Cbfc998ef595bccea5bc8593a4527152

2 am is daytime? ;-)

over 1 year ago ·
4840
43ea08b4fc547e8a5da87c207bea2123

@finnpauls Good catch, changed it to "if (n > 19 || n < 6)"

over 1 year ago ·
8740

Hallo
i try this but unfortunately don't work http://testandproof.com/test.html

over 1 year ago ·