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

What occurs if we trigger an emit event on a socket that is already disconnected?

If the socket is already disconnected, what are the potential consequences of executing the code below? socket.emit("event", event_data); ...

What is the method for assigning a value to a variable in xhr.setRequestHeader?

I'm working on setting a value to the variable in xhr.setRequestHeader(Authentication, "Bearer" + parameter); with xmlhttprequest. Can you provide guidance on how to effectively pass a value to the variable within xhr.setRequestHeader? ...

Issue with Electron application encountered during relocation of build directory

Currently, I am developing an Electron-App using NPM that functions as an installer by unzipping a file to a specified directory. While everything works smoothly when I build the application and run it from the win-unpacked folder, moving the folder to a d ...

Updating and showing a variable in a PHP file using JavaScript within an HTML webpage

My goal is to establish a variable in a PHP file on my server named "likes." Subsequently, I wish to incorporate a like button on my HTML webpage that, when clicked, will utilize JavaScript to modify the "likes" variable in the PHP file and increase it by ...

Tips for effectively incorporating additional directives into a directive as it is being defined

I'm encountering a significant issue with dynamic directives in angularjs. My goal is to include new directives to a directive while defining it through an object: compile: function () { return { pre: function (scope, iElement, iAttrs) { ...

Exploring the capabilities of Angular and UIGrid for fetching table information

I have been utilizing Angular along with uigrid, which is an excellent library for displaying data in a tabular format. Everything looks good when displaying the table. However, when I update an item and click on a Save button that triggers a rest service ...

The initial call to the method results in an undefined return value

In my code, there is a function that retrieves distinct values from a database. Here's how it looks: function getUniqueCategories(res, req) { query = `SELECT DISTINCT name FROM product_category;`; connection.query(query, function (err, rows) { ...

JQuery hover effect for dynamically added elements

Currently, I am working on a webpage that will trigger an ajax call upon loading. The response data in JSON format will be processed and the elements will then be added to the DOM as shown below: $.ajax({ type: 'POST', url: "http://mysite.de ...

Reduce XSLTProcessor output by 50%

I have a persistent problem (from my perspective, at least). Every time I use XSLTProcessor.transformToFragment, the output is consistently halved compared to the input. For example, when I receive 200 entries in an XML file as a response from a webservi ...

Replace Ajax Success Function

Looking to customize the behavior of the jQuery ajax function by handling a default action upon successful execution, while still running the callback function specified in the options parameter. Essentially, I need to filter out specific tags from the res ...

The CSS and Bundle script path may need adjustment following the creation of the index.html file by WebPack

There seems to be an issue with webpack trying to add 'client' to the href of script tags for my CSS and bundle files. This is causing a problem as it's incorrect and I'm unsure how to remove it. Prior to switching to webpack, here&apo ...

Tips for preventing a child div from moving when scrolling towards it and creating an internal scroll with a smooth animation using either JavaScript or jQuery

Looking to add scrolling functionality with animation to a child div on my webpage? Check out this example. I attempted using JavaScript's on scroll function, but it didn't work as expected. Currently, I have it set up to trigger on click of cer ...

I am struggling to understand why clicking this button is not successfully submitting the form to Google Sheets

I am facing an issue with my Google Sheet setup that collects form data from my website. The problem is, I am unable to link the event to a button that already exists ('CompleteOrder'). Strangely, it works perfectly fine if I add a new button: & ...

Selenium Assistance: I'm encountering a scenario where on a webpage, two elements share the same Xpath, making it difficult to differentiate them based on even

At index [1], both elements are identified, but at index [2], nothing is identified. The key difference between the two is that one has display:none, and the other has display:block. However, their involvement in determining these fields is minimal due to ...

Can the value of a variable be passed as seen in the JavaScript code snippet?

I'm wondering if I'm on the right track with generating random colors when a button is clicked. Here's my code: randomColor = "#" + Math.floor(Math.random() * 16777215).toString(16); // --- more code --- changeHeaderColor() { con ...

The addClass() method seems to be malfunctioning following an ajax request

My current project involves setting up an AJAX call that is triggered when a user clicks on an anchor link. Once the AJAX operation is successful, I want to dynamically add a class to the specific anchor that initiated the call. The script itself seems to ...

What is the proper method for invoking object (class) methods from a router?

My apologies for the vague title. Let me clarify what I am attempting to accomplish. In this scenario, there are two main components: A class called 'wallet.js' A router named 'index.js' which handles GET requests This is my objectiv ...

After a certain period of time, the NodeJs exec() function ceases to create additional

I am in the process of developing a BLE scan module on nodeJs using Bluez. Below is the code snippet I have implemented: exec('sudo hcitool lescan --duplicates &', function (error, stdout, stderr) { }); exec('sudo hcitool lescan --dupl ...

Transferring JSON data through AJAX to a PHP backend

I have been working on a solution to convert a CSV file into JSON and then send it to BigCommerce using their REST API. Initially, I planned to use Javascript for the entire process, and everything was successful until I encountered issues with CORS when t ...

Running an npm audit on the project reveals numerous errors and vulnerabilities

After running npm audit on my React project, I was presented with an extensive list of issues that needed attention. # npm audit report postcss 7.0.0 - 8.2.9 Severity: moderate Regular Expression Denial of Service - https://npmjs.com/advisories/1693 fix ...