Search code examples
javascripthtmlcsscomparison-operators

Changing a background image of <body> (in CSS) depending on the season (Current Calendar Month)


I'd like to change my HTML background depending on the date, but what I've written isn't working properly. I can't find any applicable examples and I'm struggling to complete it.

I just want the start of a new season to change the background of my HTML page by altering the image used in my CSS file.

JavaScript:

var d = new Date();
var Day = d.getDate();
var Month = d.getMonth();
if (Month == <3 && Month == 5) {
    document.background-image: url("springTree.jpg");
} else if (Month == < 6 && Month == > 8) {
    document.background-image: url("summerTree.jpg");
} else if (Month == < 9 && Month == > 11) {
    document.background-image: url("autumnTree.jpg");
} else (Month == 12 && Month == > 2) {
    document.background-image: url("winterTree.jpg");

CSS:

div.body {
  background-image: url("summertree.jpg");
    width: 640px;
    height: 1136px;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
    background-size: cover;
}

I'm not sure if this could be accomplished with JQuery but I'm willing to experiment with anything.

As you can see I clearly have no clue what I'm doing and I'm in need of some help, thanks.


Solution

  • I suggest you to use class injection into the <html> tag. Javascript code will inject whatever class you want (depending on location (winter vs summer) or local time (day vs night)). And your css will have the backgrounds (or any other differences accordingly.

    CSS:

    .spring {background-image: url("springTree.jpg");}
    .summer {background-image: url("summerTree.jpg");}
    ...
    

    You can also have other differences:

    .spring li a {color: green}
    .winter li a {color: white}
    

    You can set the class from javascript like this:

    var html = document.getElementsByTagName('html')[0];
    html.setAttribute('class', 'spring');
    

    Or if you want multiple classes inject (add) the one you need:

    root.classList.add('evening');
    

    With your conditions:

    var d = new Date();
    var month = d.getMonth() + 1;
    var html = document.getElementsByTagName('html')[0];
    if (month >= 3 && month <= 5) {
        root.classList.add('spring');
    } else if (month >= 6 && month <= 8) {
        root.classList.add('summer');
    } else if (month >= 9 && month <= 11) {
        root.classList.add('autumn');
    } else(month == 12 || month <= 2) {
        root.classList.add('winter');
    }