JavaScript unable to dynamically change CSS styles

I've been struggling to get the color updates working for a while now. My suspicion is that my string return may be invalid, causing the issue. I'm aiming to convert hours, minutes, and seconds into hexadecimal values, but it seems to be failing for some reason. Any assistance on this matter would be greatly appreciated. Thank you!

var div = document.getElementById("full");

function getClockColor() {
  var h = toString(today.getHours());
  var m = toString(today.getMinutes());
  var s = toString(today.getSeconds());
  color = '#' + h + m + s;
  return color;
}

function changeColor() {
  div.style.backgroundColor = getClockColor();
}

setInterval(changeColor, 1000);
body {
  overflow: hidden;
  margin: 0;
  padding: 0;
}

#full {
  position: absolute;
  height: 100%;
  width: 100%;
}
<link rel="stylesheet" type="text/css" href="/Users/zanolon/Desktop/Color Clock/Clock.css">

<div id="full"></div>

Answer №1

You have encountered several issues:

  1. There is an incorrect use of the return statement outside of the getclockColor function, along with an extra }.
  2. It seems that the today object is missing. To create a new Date object with the current date, you can use new Date().
  3. While not an error, unnecessary conversion of numbers to strings is mentioned. The values will automatically convert to strings when concatenated with the + operator.
  4. In case a number has only one digit, it is advisable to add a zero. Otherwise, the generated string may have less than 6 digits (besides the #).
  5. The concept of combining three "random" numbers into a string for a hex color may not always yield a valid result. Consider utilizing the hsl format such as hsl(120, 100%, 50%) with string templates as hsl(${h}, ${m}%, ${s}%).

var div = document.getElementById("full");

function getclockColor() {
  const today = new Date()
  var h = today.getHours();
  var m = today.getMinutes();
  var s = today.getSeconds();
  color = '#' + h + m + s;
  return color;
}

function changeColor() {
  div.style.backgroundColor = getclockColor();
}

setInterval(changeColor, 1000);
body {
  overflow: hidden;
  margin: 0;
  padding: 0;
}

#full {
  position: absolute;
  height: 100%;
  width: 100%;
}
<link rel="stylesheet" type="text/css" href="/Users/zanolon/Desktop/Color Clock/Clock.css">

<div id="full"></div>

Answer №2

Here are a few things to address:

  • Ensure you do not have an extra closing } as it can cause an illegal return statement error when not within a function scope.
  • Make sure to initialize the variable today before using it in your code.
  • The method toString() should be called on a number, not as a standalone function. Use it like this: today.getHours().toString()
  • To avoid issues with invalid hex codes, consider padding the hours, minutes, and seconds with a leading zero if they are less than 10.

Check out the code snippet below. The color may change due to the hex code:

var div = document.getElementById("full");

function getclockColor() {
    var today = new Date();
    var h = today.getHours().toString();
    var m = today.getMinutes().toString();
    var s = today.getSeconds().toString();
    var color='#'+h+m+s;
    return color;
}

function changeColor() {
    console.log(getclockColor());
    div.style.backgroundColor = getclockColor();
}

setInterval(changeColor, 1000);
body {
  overflow: hidden;
  margin: 0;
  padding: 0;
}

#full {
  position: absolute;
  height: 100%;
  width: 100%;
}
<div id="full"></div>

To fix potential padding issues, see the modified code snippet below (Utilizing the pad function):

var div = document.getElementById("full");

function pad(n, width, z) {
  z = z || '0';
  n = n + '';
  return n.length >= width ? n : new Array(width - n.length + 1).join(z) + n;
}

function getclockColor() {
    var today = new Date();
    var h = today.getHours().toString();
    var m = today.getMinutes().toString();
    var s = today.getSeconds().toString();
    var color='#'+pad(h,2)+pad(m,2)+pad(s,2);
    return color;
}

function changeColor() {
    console.log(getclockColor());
    div.style.backgroundColor = getclockColor();
}

setInterval(changeColor, 1000);
body {
  overflow: hidden;
  margin: 0;
  padding: 0;
}

#full {
  position: absolute;
  height: 100%;
  width: 100%;
}
<div id="full"></div>

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

Applying a class in jQuery to an element when the data attribute aligns with the current slide in Slick

I need to compare the data-group attribute of the current slide to the equivalent attribute in a navigation list. If they match, the anchor element in the navigation list should be given an active class. How can I achieve this using jQuery? Navigation Li ...

Make individual term span the entire width of 100%

Is it feasible to expand a single word like "News" to occupy 100% width of the div element? My goal is to automatically adjust letter spacing and justify individual words. Currently, I have a menu with items such as: Home About News Etc It would be idea ...

Angular - The argument provided is not compatible with the parameter

I encountered the following TypeScript errors in app.component.ts: Issue: Argument of type '(events: Event[]) => void' is not assignable to parameter of type '(value: Event[]) => void'. Description: Types of parameters 'e ...

The placement of the React.js/Next.js Loader is incorrect on the page

While I was trying to display a Loader over everything during data fetching from my API, I encountered a situation where the Loader was not appearing at the expected top level but inside the page itself. Even though the HTML tree showed it at the top level ...

Utilize the search bar within a JavaScript function

One issue I am facing is taking an input from a search box and using that value as a parameter for another function. However, every time I click the button, the global variable resets itself when the page refreshes. In my javascript code, this is what I h ...

How can you vertically center an icon button in Material UI?

Looking for help with aligning elements in this code snippet: <TextField id="outlined-basic" label="22Keyword" defaultValue={"test123"} variant="outlined" /> <IconButton aria-label="delete&q ...

Increase and decrease thumbnail size using an onclick event

https://i.sstatic.net/oDkB9.png I've been experimenting for hours to try and create a functionality where the thumbnail image on my HTML page enlarges when clicked, and then shrinks back down when clicked again. However, I'm encountering an issu ...

Tips on capturing the response data in UI testing automation

Currently, I am working on automating a login page using WebDriverIO for UI Automation. After clicking the Login button, a request to *.com/user/login is triggered in the background. I need to capture this call's response in order to obtain a token r ...

The background image does not appear to be displaying correctly on GitHub pages

I've encountered an issue where my svgs are not displaying as background-image or background on GitHub pages, even though they work fine locally. I utilized sass as a preprocessor for css, in case that detail is helpful. If anyone has insights on how ...

What is the best way to search for a specific string within an Airtable record that may also have additional data included?

By utilizing the filterByFormula method in the airtable api, I am able to query and choose records that include a specific item (string). However, this query will only return the records that exclusively have that particular string. Referencing the airtab ...

Tips for aligning multiple columns within a Bootstrap 3 carousel

For quite some time, I have been trying to solve this puzzle. My goal is to have the featured image displayed to the left of the carousel, with its associated text to the right. I've created a mockup to illustrate exactly what I mean. I can achieve t ...

What is the best way to integrate Bootstrap 5 with Next.js?

After adding Bootstrap to my project with npm install bootstrap, I included the style in /pages/_app.js like this: import 'bootstrap/dist/css/bootstrap.css'; export default function App({ Component, pageProps }) { return <Component {...pag ...

Is there a way to generate a distinctive curved design using CSS for a

I am currently using CSS and div elements in an attempt to create these particular lines: https://i.stack.imgur.com/Ytowq.png .line { width: 1px; height: 100px; background-color: black; position: absolute; border-radius: 50%/100px 1 ...

How important is a neglected parameter in the world of JavaScript?

Curious about the value of an ignored parameter in JS? Imagine a function that requires 2 values as parameters, but you only provide one during the call. What happens to the other parameter? You might think it's undefined, but the code below only show ...

JavaScript text converter using split() method

I have a large amount of data in text format, similar to the following: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0b0d1b0c1b131f17124f3e19131f1712501d1113">[email protected]</a>:token1 | Time = US | Alphabe ...

Utilizing D3.js to filter nodes and links by making multiple selections from a checkbox

I am interested in enhancing my current forced directed graph by adding more flexibility. You can access the Jsfiddle here. Currently, there are radio buttons that control the opacity of nodes and links. There are 4 types of nodes: Agent, Customer, Pho ...

Is it possible to restrict contenteditable elements to only accept numbers?

Is there a way to restrict contenteditable elements such that only numerical values can be entered? I attempted to use the following code snippet: onkeypress='return event.charCode >= 48 && event.charCode <= 57' However, despite a ...

How to utilize a Boolean return value in React Class component following a promise fetch operation

Hello, I have a question about a class I am working on in React. When I call Auth.isAuthenticated() from another component, it always returns false, even though the server is returning a 200 response which should set this.authenticated to true. How can I ...

Ways to extract information from JSON files

Currently, I am working on a script to extract viewer count and follower count data from Twitch. While I have successfully retrieved the viewer count information, I am encountering issues with extracting the follower count. The essential information can be ...

Tips for retrieving sent data from a jQuery Ajax request on XHR error

I am facing a situation where I have numerous jQuery AJAX requests being sent using a single function. function sendData(data){ $.post("somepage", {"data": data}, function() {}, "json") .fail(function(jqXHR, textStatus, errorThrown){ sendD ...