Modifying the background image of the <body> element in CSS to reflect the season based on the current month in the calendar

I'm struggling to change my HTML background based on the date. The code I've tried isn't working as expected and I can't seem to find any relevant examples to guide me.

My goal is simple - I want the background of my HTML page to be changed whenever a new season begins by swapping out the image defined in my CSS file.

Here's what I have so far:

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

This is how my CSS looks:

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 open to trying JQuery or any other suggestions to achieve this effect because, frankly, I feel quite lost on how to make it work. Any assistance would be greatly appreciated. Thanks!

Answer №1

If you're looking to dynamically change the styling of your webpage based on certain conditions, one approach is to utilize class injection into the <html> tag. With Javascript code, you can inject specific classes depending on factors like location (winter vs summer) or local time (day vs night). This allows your CSS to apply different backgrounds or other style variations accordingly.

For example, in your CSS:

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

You can also implement more detailed differences like so:

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

To set the class from Javascript:

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

If you want to add multiple classes, you can do so by injecting them as needed:

root.classList.add('evening');

Considering specific conditions, you can use Javascript to adjust the class based on various criteria:

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

Answer №2

Before proceeding, it is essential to understand how comparisons work in JavaScript. This website provides a comprehensive list of operators and their functions:

JavaScript Comparison and Logical Operators

if(Month == < 3) needs to be revised to if(Month <= 3).

When assessing your conditions, remember to vocalize them:

if (Month <= 3 && Month == 5)
if (Month <= 6 && Month >= 8)

Can the month be less than or equal to 3 and equal 5? Can it also be less than or equal to 6 and greater than or equal to 8? (Highly unlikely in any universe.)

In terms of changing images, have you reviewed your HTML structure? Is there a div with a class named body? Or are you targeting the body tag itself? If it's the latter, you can alter the background image using this code snippet.

document.body.style.backgroundImage = "url('springTree.png')";

Answer №3

Take a look at the code snippet below.

var today = new Date();
var dayOfMonth = today.getDate();
// The getMonth function returns values from 0 to 11, so we increment by 1
var monthOfYear = today.getMonth() + 1;

// Check for winter season: December, January, February
if (monthOfYear == 12 || monthOfYear <= 2) {
    document.body.style.backgroundImage = url("winterTree.jpg");
}
// Check for spring season: March, April, May
else if (monthOfYear >= 3 && monthOfYear <= 5) {
    document.body.style.backgroundImage = url("springTree.jpg");
}
// Check for summer season: June, July, August
else if (monthOfYear >= 6 && monthOfYear <= 8) {
    document.body.style.backgroundImage = url("summerTree.jpg");
}
// Check for autumn season: September, October, November
else if (monthOfYear >= 9 && monthOfYear <= 11) {
    document.body.style.backgroundImage = url("autumnTree.jpg");
}

Answer №4

It's intriguing to see your approach to JavaScript coding. I recommend checking out JavaScript | MDN - Mozilla Developer Network for tips on targeting classes and overriding styles. Here is an alternative solution.

var d = new Date();
var Day = d.getDate();
var Month = d.getMonth(); 

if (Month <= 3 || Month === 5) {
    document.getElementsByClassName('body')[0].style.background = "url('https://image.freepik.com/free-photo/my-cat-mimi_2568679.jpg')";
    console.log('1');
} else if (Month <= 6 || Month >= 8) {
    document.getElementsByClassName('body')[0].style.background = "url('https: //image.freepik.com/free-photo/clouds-above-the-volcano_426-19322758.jpg')";
    console.log('2');
} else if (Month <= 9 || Month >= 11) {
    document.getElementsByClassName('body')[0].style.background = "url('https://image.freepik.com/free-photo/my-cat-mimi_2568679.jpg')";
    console.log('3');
} else {
    document.getElementsByClassName('body')[0].style.background = "url('https: //image.freepik.com/free-photo/clouds-above-the-volcano_426-19322758.jpg')";
    console.log('4');
}

Instead of using &&, consider using || if you want to change the image between the first month and the fifth month. Brush up on JavaScript Comparison and Logical Operators at JavaScript Comparison and Logical Operators!

Remember not to write if(Month == < 3), but rather if(Month <= 3).

To learn how to target HTML classes in the DOM, check out this resource:

Javascript Class Targeting

Ps: Explore a working Fiddle here Change Pic depending using Dates

Keep learning and have fun! Cheers :)

Answer №5

var currentDate = new Date();
var dayOfMonth = currentDate.getDate();
var monthOfYear = currentDate.getMonth();

if (monthOfYear >= 3 && monthOfYear <= 5) {
    document.background-image: url("springTree.jpg");
} else if (monthOfYear >= 6 && monthOfYear <= 8) {
    document.background-image: url("summerTree.jpg");
} else if (monthOfYear >= 9 && monthOfYear <= 11) {
    document.background-image: url("autumnTree.jpg");
} else if (monthOfYear == 12 || monthOfYear <= 2) {
    document.background-image: url("winterTree.jpg");

Please review all your conditions. For example: Month==12 and Month<=2 should be updated to (Month == 12 || Month > 2) to avoid conflicting statements.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue: Module 'serialize-javascript' not found despite being present in the 'node_modules' directory after executing npm start command in ReactJS project

My npm start suddenly stopped working. This issue arose after I switched to an unused branch with unrelated histories, made some changes, pushed them (unaware that the branch was outdated), then used git checkout -f "" to go back to the recent br ...

How can I remove the gaps between Bootstrap panels on a website?

The Issue https://i.stack.imgur.com/I5EFR.png My problem is with the spacing between the panels, highlighted in red. I've attempted to remove them by using the following CSS: .panel { margin-top: 0; margin-bottom: 0; padding-top: 0; ...

Issue with displaying Bootstrap 3 modal on Mozilla browser

Hello everyone, I've encountered an issue with my Bootstrap modal on Mozilla browser. Everything works perfectly on Chrome and Safari, but when I click the modal button in Mozilla, nothing happens. Here's a snippet of my code: <button type="b ...

Encountering an issue with importing createSagaMiddleware from 'redux-saga' while working on my create-react-app project

Within my create-react-app, I have the following import: import createSagaMiddleware from 'redux-saga'; However, there seems to be an issue with importing createSagaMiddleware in my system. The versions I am currently using are: node 12.13.0 n ...

Steps to dynamically populate a datatable with JSON data by triggering a click event in jQuery

I am facing an issue with feeding JSON data into datatables when the search button is clicked. The JSON data structure is as follows: [ { "port_code":"BOM", "cont_details_id":"9", "price":"44.000", "cont_price":"500", "c ...

Creating a connection between my .html and .ejs files: A step-by-step guide

I have successfully created a pair of HTML files - index.html & contact.html. Within these files, I have implemented a navigation bar that allows for seamless transition between them. Recently, I delved into the realm of retrieving APIs and crafted an app ...

Update ng-Bootstrap ToDate field by removing the date when selecting a fromDate

Is there a way to clear the date from the toDate input field while selecting a date from the fromDate input field in ng-bootstrap? <form class="row row-cols-sm-auto" *ngIf="showDateRangeImp"> <div class="col-12" ...

Looping the jQuery Ajax success function

Utilizing Ajax to input an array of data into a database. At the moment, when clicking on "#bookingbutton," it triggers a return block of HTML containing the ".select-room-button" button. I have incorporated the code for ".select-room-button" within the ...

Modify a class attribute within a function

I need to modify the this.bar property within my class when a click event occurs. The issue is that the context of this inside the click function is different from the this of the class. export class Chart { constructor() { this.bar; } showC ...

Typescript does not allow for extending an interface with a data property even if both interfaces have the same data type

I've encountered a peculiar problem with Typescript (using Visual Studio 2012 and TypeScript v0.9.5) that I could use some help clarifying. The code snippet below functions correctly: interface IA { data: any; } interface IB { data: any; } ...

Accessing a JavaScript URL beyond the Facebook frame application

I have developed a Facebook application with a navigation menu, and I am seeking a way to open links outside of the iframe app. Is it possible to achieve this? Currently, I am using the code below which loads inside the iframe but I am unable to get it t ...

Using custom woff2 fonts in Android applications created with Visual Studio Community and Cordova seems to be causing compatibility issues

Help Needed! I am facing an issue with my app created using Visual Studio Community and Cordova. Everything works perfectly when I simulate it on my PC, but when I install it on my phone, the fonts just won't display correctly. I have tried all the s ...

Can I update a label using ajax from the controller?

Hello everyone, I am facing a challenge in changing the text label coming from my Controller's JsonResult. There are two specific issues that I am encountering: 1) I am having difficulty displaying the text sent from my controller onto my view... ...

In Chrome, CSS automatic hyphens are displayed as question mark symbols

On my website, I have implemented automatic hyphenation using CSS: article > p, article > li { -o-hyphens: auto; -o-hyphenate-limit-before: 3; -o-hyphenate-limit-after: 3; -o-hyphenate-limit-chars: 6 3 3; -o-hyphenate-limit-lines: 2; -o-h ...

Unable to retrieve or remove cookie sent from Express on client side

My Express server is sending a cookie to the client that is not httpOnly. Despite this, the client is unable to access the cookie through document.cookie or see it in the Application tab on chrome dev tools. Interestingly, I am able to view the cookie in C ...

Modify the background color of a particular TD element when clicking a button using JavaScript and AJAX

When I click on the "Active account" button inside the designated td with the <tr id="tr_color" >, I want the value "1" to be added to the 'active_account' column in the database. I have been successful with this functionality. However, I a ...

Utilizing Angular's Local Storage Module to efficiently store and manage various elements within an array in Local Storage

I'm facing an issue with storing and retrieving an array from localStorage using the Angular Local Storage Module. Despite following the necessary steps, I am only able to retrieve the last element added to the array. Can anyone provide insights on wh ...

Is there a function called 'onViewportChange' in media queries that triggers a search in the .css file for applicable styling?

So I'm not entirely sure about all the specifics, but my understanding is that each time a new HTML element is created, it checks through all linked CSS files and inline styles to see if those styles should be applied to that element. This suggests t ...

Struggling to Make Text Overlay Transparent and Slide Only to the Right

Can someone help me make my image have an opaque overlay with text that slides only right when hovered over? Currently, it's sliding both right and up. Any suggestions on how to fix this issue would be greatly appreciated. Thank you. html, body{ ...

Using Vue to alter data through mutations

Greetings! I am currently in the process of developing a website for storing recipes, but as this is my first project, I am facing a challenge with modifying user input data. My goal is to create a system where each new recipe added by a user generates a u ...