Can the background color of a webpage be altered depending on the time of day?

https://jsfiddle.net/8x7p682z/

function initialize() {
  function setThemeForTimeOfDay() {
    const body = document.querySelector('body');
    const hours = new Date().getHours();

    if (9 <= hours && hours <= 12)
      body.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 231, 255),rgb(39, 38, 38))';
      if (hours > 12 && hours <= 15)
      body.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
    else
      body.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
  }

  function initialize1() {
    function setThemeForTimeOfDay() {
      const body = document.querySelector('body');
      const hours = new Date().getHours();

      if (9 <= hours && hours <= 12)
        body.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 231, 255),rgb(39, 38, 38))';
        if (hours > 12 && hours <= 15)
        body.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
      else
        body.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
    }

    setThemeForTimeOfDay();
    setInterval(setThemeForTimeOfDay, 60000);
  }

These are my codes. I implemented javascript to modify the background color and navbar selection color depending on the user's time. However, it is not working as expected. Can someone please assist me with this issue? I am completely new to this.

Answer №1

I have revised the script to address some issues.

  1. I eliminated all the onload calls from the HTML, ensuring that the functions are available when needed.

  2. I added an id="nav_menu" to the menu.

Furthermore, I made adjustments to the code below.

function init() {
  const body = document.querySelector('body');
  const hours = new Date().getHours();
  const ul = document.getElementById('nav_menu')

  if (9 <= hours && hours <= 12) {
    body.style['background-image'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 231, 255),rgb(39, 38, 38))';
    changeMenuColor('linear-gradient(to right, rgb(39, 38, 38), rgb(96, 231, 255),rgb(39, 38, 38))');
  } else if (hours > 12 && hours <= 15) {
    body.style['background-image'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
    changeMenuColor('linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))');
  } else
    body.style['background-image'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
  changeMenuColor('linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))');
}

function changeMenuColor(color) {
  elements = document.getElementsByClassName('navbar-menu');
  for (var i = 0; i < elements.length; i++) {
    elements[i].querySelector('a').style['background-image'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
  }
}

init();

Anticipating that this update proves beneficial!

Answer №2

Here are some recommendations for managing your conditions:

function start() {
  function setThemeForTimeOfDay() { 
    const body = document.querySelector('body');
    const hours = new Date().getHours();

    if (9 <= hours && hours <= 12) {
      body.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 231, 255),rgb(39, 38, 38))';
    } else if (hours > 12 && hours <= 15) {
      body.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
    } else {
      body.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
    }
  }
}

function start1() {
  function setThemeForTimeOfDay() { // <-- It is recommended to avoid duplicate function names
    const body = document.querySelector('body');
    const hours = new Date().getHours();

    if (9 <= hours && hours <= 12) {
      ul.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 231, 255),rgb(39, 38, 38))';
    } else if (hours > 12 && hours <= 15) {
      ul.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
    } else {
      ul.style['background-color'] = 'linear-gradient(to right, rgb(39, 38, 38), rgb(96, 255, 207),rgb(39, 38, 38))';
    }
  }

  setThemeForTimeOfDay();
  setInterval(setThemeForTimeOfDay, 60000);
}

Using brackets for visibility and using tidy buttons can help with code organization.

For more information, visit: https://www.w3schools.com/js/js_if_else.asp

I hope this information is helpful.

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 is the best way to use JavaScript to fill in missing images with alternative HTML content?

As a provider of a service that helps users find the location of pictures, I face a challenge due to the fact that the pictures are stored on another internal site. Some users may not have access to this site as my service offers additional information. Th ...

Make sure to use dispatch when updating the array to prevent any potential infinite loops

I am currently working with JSX to create a function that reads user profiles and updates them upon clicking a button. The object userProfiles contains existing user profile data, which should be updated by combining the current contents with those from ne ...

Guide to creating an uncomplicated quiz using PHP

My goal is to create a quiz with 15 questions. Every time a user lands on the page, they will see a random selection of 5 questions. Each question will have 4 multiple choice answers, with one being correct. The marks allocated for each question are 20, 15 ...

Tips for adding a console.log statement to material-ui components to confirm the object/array/value

An issue arises in my React JS code snippet execution that I need help with: <TableBody> { (data.length > 0) ? ( data.map((x, i) => row( x, i, formColumns, handleRemove, handleSelect, editIdx ))) : (<TableRo ...

CSS code influencing unintended elements

www.geo-village.com <- Live Example After setting up my main webpage with CSS and PHP files, I noticed an issue with the navigation bar. Despite having a separate PHP and CSS file for the navigation bar items, the Login and Register buttons on the main ...

Creating models or bulk creating promises in a seed file

When working with a promise chain to add data in JavaScript, I usually start by using Node.js or another method and it works fine (with some variations). However, when attempting to implement this promise chain in a sequelize seed file with the sequelize- ...

managing nested JSON arrays in JavaScript

I have a straightforward task with handling a simple array that is divided into two parts: a group of vid_ids and a single element named page. Initially, I was iterating through the vid_id array using a for loop. However, upon adding the page element, I en ...

Creating formatted code blocks within my HTML document

I'm currently working on achieving this layout in my HTML: https://i.stack.imgur.com/2LEQO.png Here is the JSFiddle link: https://jsfiddle.net/cr9vkc7f/4/ I attempted to add a border to the left of my code snippet as shown below: border-left: 1px ...

Is it advisable to switch the doctype from HTML 4.01 or XHTML 1.0 to HTML5 for a web page?

When updating a legacy website to be more modern and "HTML5"-ish, is it considered safe to simply change the heading doctype as shown below? <!doctype html> The original doctype could be: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitiona ...

AngularJS - $scope.$destroy does not eliminate listeners

I am currently exploring how to develop my own "one-time binding" functionality for AngularJS version 1.2 and earlier. I came across this response which explains the process of creating a custom bindOnce directive. Upon using the provided directive: a ...

Best method for creating HTML elements with jQuery

I've come across various styles and methods for creating elements in jQuery, each with its own unique approach. I am interested in discovering the most effective way to construct elements and whether a specific method stands out as superior for any pa ...

Comparing unique values between objects in JavaScript with varying keys

I'm facing a peculiar issue that I can't seem to solve. I have two variables named nft and web3.givenProvider. Both of them have an address value of "0x0000000000000", but they are stored under different keys - nft is under .seller and ...

What are some React component libraries compatible with Next.js 13.1?

I'm exploring Next.js and experimenting with version 13.1 and the new app directory. Is it feasible to accomplish this without sacrificing the advantages of server controls? An error message I encountered states: You're attempting to import a c ...

How to retrieve text values across various browsers using Vue.js

Whenever I type something in a text box, it displays the text value based on its ID. This code works perfectly when running it on my laptop at http://localhost:8080/. If I open the same website on my phone at http://xxx.xxx.x.xxx:8080/, it shows the same ...

Issue with Bootstrap Navbar dropdown functionality not functioning correctly in browsers, but working fine on Codepen

I'm encountering an issue with a dropdown menu in the navbar of my document. The dropdown menu works fine in my codepen but not in my text editor (Sublime). I've tried various solutions and couldn't find a fix, so I'm reaching out here ...

Utilizing Ajax to dynamically populate table columns

I have an HTML table with specific labels and styles. I am looking for a way to update the table by using the unique 'id' of each row/element and populate the data using Ajax. Can anyone provide a solution or suggestion? <table border="0" ...

Purchase Now with Paypal Button

Just starting out with PHP and PayPal buttons! Important: Referring to Mysql items here. I'm attempting to set up an online shop, but I have a concern about PayPal "Buy Now" buttons. If a customer purchases an item, the website receives the money, b ...

Looking for assistance in transferring information from one webpage to another dynamic webpage

I'm in the process of building a website to feature products using NextJs. My goal is to transfer data from one page to another dynamic page. The data I am working with consists of a json array of objects stored in a data folder within the project. Wh ...

Tips for employing the slice approach in a data-table utilizing Vue

I have a unique situation in my Vue app where I'm utilizing v-data table. The current display of data in the table works fine, but I now want to enhance it by incorporating the slice method. Here is the current data displayed in the table: https://i ...

What is the best way to maximize the use of the space available until reaching a div with varying dimensions each time

I have a div on the left that displays a name, and it can vary in length. On the right, there is another div with buttons. The number of buttons may change, so I am unsure how many will be displayed. Is there a way to utilize only CSS to make sure the fi ...