Is it possible to modify the colors within a JavaScript string?

I am currently working on creating a multi-timezone clock that will be shown in a web browser in kiosk mode.

The basic code was taken from and the kiosk setup from: and then customized into: However, I am struggling to change the color of each timezone displayed.

Since JavaScript is not my forte, any guidance would be greatly appreciated if I'm on the wrong track.

Thank you in advance!

This is what I have so far in terms of code (87 lines):

"use strict";

var textElem = document.getElementById("clocktext");
clocktext.setAttribute('style', 'white-space: pre;');
var targetWidth = 0.90;
var curFontSize = 20;

function updateClock() {
  var d = new Date();
  var s = "";
  s += "UTC - "
  s += (10 > d.getUTCHours() ? "0" : "") + d.getUTCHours() + ":";
  s += (10 > d.getUTCMinutes() ? "0" : "") + d.getUTCMinutes() + ":";
  s += (10 > d.getUTCSeconds() ? "0" : "") + d.getUTCSeconds();
  s += '\r\n';
  s += "Loc - "
  s += (10 > d.getHours() ? "0" : "") + d.getHours() + ":";
  s += (10 > d.getMinutes() ? "0" : "") + d.getMinutes() + ":";
  s += (10 > d.getSeconds() ? "0" : "") + d.getSeconds();
  textElem.textContent = s;
  setTimeout(updateClock, 1000 - d.getTime() % 1000 + 20);
}

function updateTextSize() {
  for (var i = 0; 3 > i; i++) { 
    curFontSize *= targetWidth / (textElem.offsetWidth / textElem.parentNode.offsetWidth);
    textElem.style.fontSize = curFontSize + "pt";
  }
}

updateClock();
updateTextSize();
window.addEventListener("resize", updateTextSize);


$(document).ready(function() {
  // iOS web app full screen hacks.
  if (window.navigator.standalone == true) {
    // make all link remain in web app mode.
    $('a').click(function() {
      window.location = $(this).attr('href');
      return false;
    });
  }
});
@font-face {
  font-family: "Digital-7";
  src: url(digital-7.ttf) format("truetype");
}

p.customfont {
  font-family: "Digital-7";
}

html {
  background: #000000;
  font-family: "Digital-7", sans-serif;
  font-weight: normal;
  color: #00ffff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html style="height:100%; margin:0; padding:0">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name='viewport' content='width = device-width, initial-scale = 1, minimum-scale = 1, maximum-scale = 1, user-scalable = no, viewport-fit=cover'>
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="apple-mobile-web-app-title" content="Ampron Clock">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>GeekHo Clock</title>

</head>

<body style="display:flex; height:100%; margin:0; padding:0; justify-content:center; align-items:center">

  <span id="clocktext" style="font-kerning:none"></span>

</body>

</html>

Answer №1

There are multiple approaches you can take to achieve your objective. I have opted for the method that seamlessly integrates into your existing code.

  1. Encapsulate the timezones with <span> tags and assign them a class for styling with the new color
  2. Replace: textElem.textContent = s; with textElem.innerHTML = s;
    • This is safe in this context as you have full control over the content.
  3. Include a CSS class (tz) and specify the new color.

If you require distinct colors for each timezone, use different class names with varied color definitions in CSS.

"use strict";

var textElem = document.getElementById("clocktext");
clocktext.setAttribute('style', 'white-space: pre;');
var targetWidth = 0.90; // Proportion of full screen width
var curFontSize = 20; // Do not change

function updateClock() {
  var d = new Date();
  var s = '<span class="tz">UTC</span>';
  s += " - "
  s += (10 > d.getUTCHours() ? "0" : "") + d.getUTCHours() + ":";
  s += (10 > d.getUTCMinutes() ? "0" : "") + d.getUTCMinutes() + ":";
  s += (10 > d.getUTCSeconds() ? "0" : "") + d.getUTCSeconds();
  s += '\r\n';
  s += '<span class="tz">Loc</span>';
  s += " - "
  s += (10 > d.getHours() ? "0" : "") + d.getHours() + ":";
  s += (10 > d.getMinutes() ? "0" : "") + d.getMinutes() + ":";
  s += (10 > d.getSeconds() ? "0" : "") + d.getSeconds();
  textElem.innerHTML = s;
  setTimeout(updateClock, 1000 - d.getTime() % 1000 + 20);
}

function updateTextSize() {
  for (var i = 0; 3 > i; i++) { // Iterate for better convergence
    curFontSize *= targetWidth / (textElem.offsetWidth / textElem.parentNode.offsetWidth);
    textElem.style.fontSize = curFontSize + "pt";
  }
}

updateClock();
updateTextSize();
window.addEventListener("resize", updateTextSize);


$(document).ready(function() {
  // iOS web app full screen hacks.
  if (window.navigator.standalone == true) {
    // make all link remain in web app mode.
    $('a').click(function() {
      window.location = $(this).attr('href');
      return false;
    });
  }
});
@font-face {
  font-family: "Digital-7";
  src: url(digital-7.ttf) format("truetype");
}

p.customfont {
  font-family: "Digital-7";
}

html {
  background: #000000;
  font-family: "Digital-7", sans-serif;
  font-weight: normal;
  color: #00ffff;
}

.tz {
  color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html style="height:100%; margin:0; padding:0">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name='viewport' content='width = device-width, initial-scale = 1, minimum-scale = 1, maximum-scale = 1, user-scalable = no, viewport-fit=cover'>
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
  <meta name="apple-mobile-web-app-title" content="Ampron Clock">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>GeekHo Clock</title>

</head>

<body style="display:flex; height:100%; margin:0; padding:0; justify-content:center; align-items:center">

  <span id="clocktext" style="font-kerning:none"></span>

</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

"Combine data streams efficiently with RxJS using #groupBy to create groups of observable

I am trying to zip grouped observables in order to form the cartesian product of related groups. However, when I run the code below, only the child observable groups emit values inside the #zip function - why is that? Link to code snippet var parent = Rx ...

Encountered JSON array, unable to retrieve certain attributes in AngularJS

I have developed a web service that organizes my information into a list and then converts it to JSON format. Below is the JSON output: { GetEventLTResult: [ { eventID: 1, location: "Place A", type: "Communi ...

tips for showcasing an item in a tooltip within a data table

I am working on dynamically creating a table with data retrieved from an ajax response. My goal is to display the data stored in an object within a tooltip attached to each cell. Currently, I have successfully rendered the table, but it is displaying `[obj ...

React Resize Detection: Handling Window Resize Events

Is there a more efficient way to listen for the window resize event in react.js without causing multiple callbacks? Perhaps a React-oriented approach (like using a hook) to achieve this? const resizeQuery = () => { console.log("check"); if ( ...

Tips for sending parameters using arrow functions within ReactJS hooks

I've recently started working with ReactJS and I'm a bit confused about how to pass parameters using arrow functions. I attempted to use .bind() in order to bind the value so it can be used in the function, but unfortunately that didn't work ...

What is the best way to invoke a function within an AngularJS controller?

Currently, I am exploring the most efficient method of calling a function from an AngularJS controller externally. In our setup, data is transmitted from a Python backend to the frontend using JavaScript functions. To feed this data into the Angular contr ...

Guide on how to trigger a pop-up modal to open a new webpage by clicking on a hyperlink

I have a page called one.html that has a link on it <a href="#">Click to open second page<a/> When this link is clicked, I would like for second.html to open in a popup modal. The second page contains a basic table that I want to di ...

Leveraging the power of map in an Angular typescript file

I've been attempting to populate a Map in Angular by setting values dynamically. When certain buttons are clicked, the onClick function is invoked. typeArray: Map<number,string>; Rent(movieId: number){ this.typeArray.set(movieId,"Rental ...

Is there a way to launch my JavaScript project locally and have index.html served on an npm server?

I am currently attempting to launch a specific Single Page Application (SPA) project using pure JavaScript. This project consists of a script file and an index.html file. I am trying to run this project on my local machine, but it requires that it be hos ...

Exploring Methods to Iterate through an Object Utilizing Two Arrays

Attempting to iterate through states passed as props in another component state = { question:[firstQ, secondQ, thirdQ], tag:[[1,2,3],[4,6],[a,b,c,d]] } I aim to display it on the next Componet with a pattern like: FirstQ [tag1] SecondQ ...

Troubleshooting problems with scrolling on JavaScript in Edge, Opera, and Chrome

Currently, I am developing a fun CSGO-inspired box opening feature on my food recipe website that randomly selects recipes for users. However, I have encountered some challenges with the scrolling functionality. It seems to be incompatible with certain bro ...

Checking for the existence of a Vue.js component

In the ready: method of the root instance, I have certain tasks to perform but only if some components are not present (not declared in the HTML). Is there a way to verify the existence of a component? ...

The ng-click event for the reset button is limited to a single use

There seems to be a problem with the reset button functionality on my webpage. Although it initially works, it only works once and then requires a reload of the page to function again. Here is the JS code: var ctrl = this; var original_device = angular.c ...

Issue with React component timer becoming unsynchronized with numeric input field

My number field and countdown timer are not staying synchronized. Even though I can start and pause the countdown, whenever I try to change the number value after pausing, the numbers get out of sync. The gap between the two values keeps growing as time p ...

Ways to determine the completion of the compilation process in Angular using the $compile service

Imagine having a popup directive that inherits a string template for the content it should display from the $scope. scope: { template: '=popInfo'//<div another directive></div> } This template string may even include another dire ...

Personalize your material-ui popover

Seeking assistance in customizing the shape of a material-ui popover similar to the one depicted in the image. https://i.sstatic.net/l5uNL.png I have created a working demo of the popover using React and provided a link for editing purposes. Any help? =& ...

"Utilize AJAX to submit the value of the text box input from a jQuery slider when the Submit Button

Whenever I adjust the sliders, the value is shown in an input textbox. However, when I move the slider and check the values echoed from the textboxes on another PHP page, they are always displaying as 0. Even after clicking the submit button, it still echo ...

What could be the reason for the malfunctioning of the header() function in PHP

Currently, I'm utilizing AJAX to facilitate user registration for a service. Here's the code snippet for the submit button: <input type="button" id="register" name="register" class="btn btn-success" onclick="registration();" value="Register"/ ...

Enable divs to be interactively chosen

I have created two selectable divs that function like buttons. By using the left and right arrow keys, I am able to select one of the divs with this code: document.addEventListener("keydown", keyDownDocument, false); function keyDownDocument(e) { var k ...

Deactivate a button on a specific tab

My setup includes two tabs: <div class="modal-body"> <form name="myForm" novalidate="novalidate"> <ul class="nav nav-tabs"> <li class="active"><a data-toggle="tab" href="#basicInfo">Info</a></li> ...