Last Updated: February 25, 2016
·
5.967K
· barnettjw

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

3 Responses
Add your response

2 am is daytime? ;-)

over 1 year ago ·

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

over 1 year ago ·

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

over 1 year ago ·