Updating background image according to the time in a specific location

I've been struggling with this issue for more than 4 hours now. None of the solutions provided on Stack Overflow seem to work for me. Here's the code snippet I've been working on:

<html>
<head>
  <style>
    .day {
      background-image: url(test2.png);
    }
    
    .night {
      background-image: url(test.png);
    }
  </style>
</head>
<body class="day" class="night">
  <script>
    setInterval(function() {
      var d = new Date();
      var n = d.getHours();
      if (n > 23 || n < 6) {
        document.body.className = "night";
      } else {
        document.body.className = "day";
      }
      console.log("test");
    }, 1000 * 60 * 60);
  </script>
</body>
</html>

My goal is to have the night background displayed from 11 PM to 7 AM, and the day background shown at other times.

I'm using placeholder images as the actual pictures contain mild graphic content. Please feel free to replace them with your own test images.

Answer №1

Your approach is spot-on and functions as expected (I replaced the images with colors due to an error on StackOverflow with your snippet).

The only downside (which may be a problem for you but a design feature for others) is that setInterval begins after the first interval is finished. In simpler terms, you had to wait for an hour to see the changes.

In my solution, I separated the JavaScript into a distinct function called by setInterval, which then triggers immediately.

I also eliminated the duplicate classes on the body since those will be set by the function itself.

Note: There might be an issue of having both day and night classes simultaneously. You should consider implementing logic to remove day when night is applied and vice versa.

Additionally, I tweaked the time equation slightly. The value of n cannot exceed 23, but it can be equal to 23. Also, as per your requirement for switching to day around 7, inclusive of 6, your equation seems correct.

As suggested by user Salman A, it's advisable to decrease the interval duration. For instance, if a user lands on your site at 6:58 and stays on a single page for an hour (assuming it's a lengthy visit), the background would change around 7:58. Hence, consider reducing the interval to perhaps 1 or 2 minutes (1000 * 60 * 1 or 1000 * 60 * 2).

<html>
<head>
  <style>
    .day {
      background-color: #ccc;
    }
    
    .night {
      background-color: #333;
    }
  </style>
</head>
<body>
  <script>
    setInterval(change_background, 1000 * 60 * 60);

    function change_background() {
      var d = new Date();
      var n = d.getHours();
      console.log(n);
      if (n == 23 || n < 7) {
        document.body.className = "night";
      } else {
        document.body.className = "day";
      }
      console.log("test");
    }

    change_background();
  </script>
</body>

</html>

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

Can images be placed on the border?

Hi there! I am trying to add an image on a border with a 100px solid width using CSS. I have experimented with positions and z-index, but I can't seem to get the desired effect. Any ideas on how to achieve this? Here is an example image: https://i.sst ...

Is background image alignment responsive?

Ensure to view it at 1680px width for perfect alignment, but resizing the screen may cause alignment issues. Any suggestions on how to resolve this problem? I am attempting to replicate my design from Dribbble shot. Snippet of code. .wrapper { pos ...

Exceeding the boundaries: Bootstrap 4 Tooltip escaping the div

When hovering over an anchor tag with tooltip attributes, the tooltip appears far away from the anchor tag. Here is the LINK - Even when inspecting element it seems to be positioned too far away. <a class="btn btn-secondary" data-toggle="tooltip" dat ...

Animating Brightness and Contrast in CSS

I come from a strong background and I am looking to create a dynamic loop that changes the brightness using CSS specifically on Chrome. The goal is to have the background color match the user's profile, providing a unique experience each time. For ex ...

The CSS animation in Firefox is limited to running only once

I am in the process of creating a tab system for beginners as an open-source project. Recently, I have come across what seems to be a bug in how Firefox handles CSS animations. Issue with Tab Animations in Firefox For the animation of each tab, I am utili ...

Automatically adjust padding in nested lists with ReactJS and MaterialUI v1

How can I automatically add padding to nested lists that may vary in depth due to recursion? Currently, my output looks like this: https://i.stack.imgur.com/6anY9.png: However, I would like it to look like this instead: https://i.stack.imgur.com/dgSPB. ...

What is the most effective approach for managing two distinct ajax calls within a Laravel application?

I am working on a page with two separate ajax calls (using Laravel). The first call triggers the second one, but the options for the second ajax are in a select box. Here is my current solution: public function getCategoryAjax(Request $request) { $pr ...

What is the best way to transform a JavaScript object into a JavaScript literal?

Currently, in my nodejs project, I have an object defined as follows: const objA = { key : 'value' }; My goal is to create a new file named obja.js which should contain the same literals from the object, rather than as a JSON literal. How can I ...

What is the technique for transmitting a child element in VueJS?

Is there a way to include HTML code in a VueJS component and have it render properly within the component? <my-vue-component> <div> ect... </div> </my-vue-component> ...

How can you modify the data within a Vue.js model using the model's method?

Trying to update the model with a simple action. After clicking the button, the data field "message" is changed to display "Good Bye!". However, it quickly reverts back to displaying "Hello Vue.Js!" immediately. How can you modify the value of the model ...

The module "ng-particles" does not have a Container component available for export

I have integrated ng-particles into my Angular project by installing it with npm i ng-particles and adding app.ts import { Container, Main } from 'ng-particles'; export class AppComponent{ id = "tsparticles"; /* Using a remote ...

Changing an element's color dynamically does not affect the color of the bullet point

When using Chrome (Version 45.0.2454.101 m), I noticed that when I add a class to a list element to change its color, the bullet point color is only updated when the window is resized or repainted. $("#a").click(function() { $("#a").addClass(&apo ...

monitoring the winstonjs logs and inserting additional parameters

Can an argument be injected into a log, like error, debug, or info, using the configuration of winston (createLogger)? I want to intercept the log and include an object in each log entry. ...

JavaScript - Utilizing an image file in relation to a URL pathway

Is there a way to reference an image URL using a relative path in a JavaScript file similar to CSS files? To test this, I created two divs and displayed a gif in the background using CSS in one and using JavaScript in the other: -My file directory struct ...

Tips for displaying axios status on a designated button using a spinner

Utilizing a v-for loop to showcase a list of products retrieved from an API request. Within the product card, there are three buttons, one for adding items to the cart with a shopping-cart icon. I aim for the shopping-cart icon to transform into a spinner ...

Tips for making a screen adapt to different monitor resolutions

Hello there! I've been working on a login screen using bootstrap 4, but I'm facing an issue with the layout. My concern is about adjusting the page layout so that the background image does not get cut off or distorted. Take a look at the image ...

Conceal the horizontal scrollbar when the navigation menu is minimized

Explaining this concept may be a bit challenging, so I have included a jsfiddle demo. The issue at hand involves a bootstrap nav menu that shifts to icons when not active and expands to include words when focused. When the menu is expanded, there are no sc ...

spacing between image tiles as you zoom in

My website features diagrams consisting of 9x9 tiles arranged in columns and rows. The final result should look like this: https://i.sstatic.net/694EH.png In the image above, the tiles are closely packed and appear as a single unit. However, when users z ...

Utilize JavaScript to assign an identifier to an element created with createElement()

As a beginner in JavaScript, I am trying to set an id into some created tags but it doesn't seem to be working. var d1=document.createElement("div"); d1.setAttribute("class","container"); var b3= document.createElement("button"); b3.setAttri ...

"Text data will be automatically cut at the end of a page and continue

I encountered the following issue As depicted in the image The data is not being displayed properly In the next td, the last character 3 is also printed on the next line Is it possible to avoid page footer and header without adjusting the page margin? ...