pithhelmet pithhelmet - 2 months ago 13
CSS Question

Changing the background image based on time of day

I have a "section" that has a background image with it.

<section id="header" class="color-light text-center" data-type="background" data-speed="10">


this is the CSS

#header {
background: url('sunrise.jpg') 50% 0 no-repeat fixed;
height: 800px;
margin: 0;
overflow: hidden;
color: #f4f4f4;
}


Using this javascript that i check the time of day...

var d = new Date();
var n = d.getHours();
if (n > 19 || n < 6)
$("#header").className = "night";
else if (n > 16 && n < 19)
$("#header").className = "sunset";
else
$("#header").className = "day";


I have this in the css file.... but not sure how or if i need to use it

/* backgrounds */
.day { background: url('sunrise.jpg') 50% 0 no-repeat fixed; }
.sunset { background: url('sunset.jpg') 50% 0 no-repeat fixed; }
.night { background: url('night.jpg')50% 0 no-repeat fixed; }


I am not sure if i am missing the way to change the #header using jquery, and apply the updated background value.

Answer

This should be all you need to do

var d = new Date();
      var n = d.getHours();
      if (n > 19 || n < 6)
        $(#header).css("background", "url('night.jpg')");
      else if (n > 16 && n < 19)
        $("#header").css("background", "url('sunset.jpg')");
      else
        $("#header").css("background", "url('day.jpg')");