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

What are some effective methods for handling error objects in REST API services?

Encountered an error object: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: YES) Type of (err): Object Now, I am looking to pass this object to another web service (REST API) What content ty ...

Transferring HTML content using jQuery AJAX and PHP

Can anyone help me with displaying the content of a division on one page to another? <div id="box-cont" class="box-content"> <?php echo $stat;// Includes multiple images and s ...

Using Javascript to make a call to load or post with jQuery

I'm not dealing with Ajax this time, but rather with JavaScript initializations. Is there a way to automatically update all the loaded elements when using $(element).load(...), in order to, for example, create a rangeInput element from an input type ...

Creating a Fixed Footer with CSS

Another question on the same topic, with a twist. Despite trying various solutions found in countless articles, none seem to work for me. My familiarity with HTML/CSS is limited due to just a few months of off-and-on practice. Hence, I'm seeking help ...

Tips for sending a parameter to an onClick handler function in a component generated using array.map()

I've been developing a web application that allows users to store collections. There is a dashboard page where all the user's collections are displayed in a table format, with each row representing a collection and columns showing the collection ...

Implementing a way to send nested objects back in response to a jQuery get request

Using jquery.get() to request data from the Spring-Boot backend: var url = "http://localhost:8080/api/v1/get_holdings?userId=1"; $.get(url, function(payload,status) { if (status == "success") { $.each ...

partial download between servers

I have been attempting to transfer/copy a large file from a remote server to my server in segmented parts or chunks. My initial approach involved utilizing a script I found here: . After making some modifications, I integrated a form into the script and e ...

What are some tips for utilizing the "bottom-row" slot within the "b-table" component in bootstrap-vue?

I am working on a component that utilizes the bootstrap-vue b-table component. My goal is to create a bottom row that displays the sum of each column in the table. However, I encountered an issue where the bottom-row only fills the first column, leaving ...

Getting started with TinyMCE in Nuxt: A step-by-step guide

I need to incorporate this script into my Nuxt code: <script> tinymce.init({ selector: "#mytextarea", plugins: "emoticons", toolbar: "emoticons", toolbar_location: "bottom", menubar: false ...

Transfer of part of a JSON object

My current setup involves an API in PHP that sends JSON data to a Javascript webpage for processing. However, when dealing with large datasets, it can strain both the user's internet connection and computer capabilities. To address this issue, I want ...

Tips for broadcasting a router event

Currently, I am working with 2 modules - one being the sidenav module where I can select menus and the other is the content module which contains a router-outlet. I am looking for the best way to display components in the content module based on menu selec ...

"Crafting a sleek card design using Material UI components in React JS

Exploring the world of material UI and looking to create a card with an image and footer. However, I'm facing challenges as there is no default option for adding a footer in the card. https://i.stack.imgur.com/xlxyb.png I want the image to be center ...

What is the functionality of the keydown event?

Whenever the input text value is not empty, I want my .removetext div to be displayed, but it's not working correctly. When I type something after the second character, my .removetext gets hidden, but it shouldn't be hidden when the input is not ...

Interacting with JSON API data in real-time using AJAX and the power of JQuery

I'm currently working on displaying data dynamically from an API, and everything is functioning well except for the "Next" and "Previous" links. I can't seem to get them to update the value count in the search bar. My problem lies in executing my ...

What is the best way to send a message to only one specific client using socket.io instead of broadcasting to everyone?

After thoroughly researching the documentation, I am still unable to find a solution. My goal is to send data to a specific client or user instead of broadcasting it to everyone. I have come across other inquiries regarding this issue, but most either rem ...

Steering your pop up to the top with CSS

Seeking advice on how to position my pop-up at the top of the page and resize it to better fit the screen. Here is where you can find my landing page: yogavoga.com/2weekdiet Grateful for any assistance provided. .modal-content { margin: 5px auto; bac ...

Sending information back to the server without causing a postback, all while remaining unseen

I have a straightforward JavaScript function on my ASP.NET page that writes data to a hidden field. However, in order to retrieve this data the form needs to be submitted back to the server. The issue is that submitting the form causes the page to reload ...

Embedding a file in a word document with a hyperlink

We are currently trying to access Word documents on our Intranet site. One of these documents contains an Excel Spreadsheet that we would like to directly link to, but we have been unable to find a solution so far. ...

When attempting to swap out ":customimage:" with an image in a React.js HTML view, the result displayed is [object Object]

I have created a function below: WordColonsToImage(comment) { var newcomment = comment.replace(/:wave:\s*/g, <img src={wavinghand} />) return newcomment } Here is an example: WordColonsToImage("Hi! :wave:") whi ...

The `.append()` function includes HTML content as plain text

I am using JavaScript to dynamically add HTML elements to my webpages. I have created a loop that iterates through all the projects, each containing multiple pictures. The first step involves generating the project title and adding it within a div element ...