pithhelmet
pithhelmet

Reputation: 2292

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.

Upvotes: 1

Views: 2815

Answers (2)

Shniper
Shniper

Reputation: 854

This should be all you need to do to make it work

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')");

Upvotes: 2

Joseph Marikle
Joseph Marikle

Reputation: 78590

className is not a property you can access through the jQuery object directly. To change a property on a jQuery object, you can use .prop(), but in this case because it's a class, you can simply use .addClass(), .removeClass(), and .toggleClass(). See here: http://api.jquery.com/category/manipulation/class-attribute/

Provided there are no other issues with the code, this should work:

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

Upvotes: 2

Related Questions