Adjust the font size in Javascript to perfectly fit the width of the page

I'm currently developing a web-based clock intended for use on an embedded device. The concept involves displaying a full-screen clock with large digits, followed by the current temperature in Fahrenheit and Celsius, as well as a city name or code beneath it. The clock's time and temperatures will be regularly updated, while the clock itself will cycle through different cities every 5 seconds.

My main challenge lies in setting the font sizes correctly. My approach is to start with a smaller font size and then adjust it iteratively until the text fills 90% of the width. This requires some mathematical calculations due to the integer nature of the offsetWidth property.

The structure includes group divisions, with separate sections for time and temperature, each set to occupy 100% of the width. The font sizes are then adjusted based on the offsetWidth of these elements relative to their parent division.

Initially, the clock's offsetWidth with a 10-point font indicates 48 when the target is 1259. Using the correct arithmetic, the font size is adjusted to around 236. However, upon inspecting the temperature section, its offsetWidth incorrectly shows as 1259 without any adjustments needed, even though it should be closer to 150.

Another issue arises where the clock sizing works initially but seems to revert back to the incorrect size after a short period, similar to the temperature section. I've checked for any issues with resetting the font sizes but remain puzzled by this behavior.

I've shared the source files (test.html and test.js) in the hope that someone can pinpoint where I might have overlooked something. Any guidance would be greatly appreciated.

test.html

<!DOCTYPE html>
<html lang='en' style="height:100%; width:100%; margin:0; padding:0">
    <head>
    <title>Full Screen Clock</title>
    <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"/>

    <style>
        /* Customizable font and colors */
        html {
            font-family: 'Courier' ;
            background:#000000;
            color: #91ff0f ;
        }
    </style>
</head>

<body style="display:flex; height:100%; width:100%; margin:0; padding:0; justify-content:center; align-items:center">
    <div style='height:100%; width: 100%; margin: 0 auto'>
        <div id='clockDiv' style='height:60%; width:100%; margin: 0 auto'>
            <span id="clocktext" style="font-kerning:none; text-align:center"></span>
        </div>
        <div id='tempDiv' style='width:100%; margin: 0 auto'>
            <span id="temptext" style="font-kerning:none; text-align:center"></span>
        </div>
    </div>

    <script src='test.js'></script>
</body>
</html>

test.js

redacted for brevity

Answer №1

It appears that both timeElem.offsetWidth and clockElem.offsetWidth consistently have the same value due to the setting of timeElem.style.display = 'block'. You may want to consider adding a flex style to see if it resolves the issue.

<!DOCTYPE html>
<html lang="en" style="height: 100%;">

<head>
  <title>title</title>
  <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" />


</head>
<style>
  /* Customizable font and colors */
  
  html {
    font-family: 'Courier';
    background: #000000;
    color: #91ff0f;
  }
</style>

<body style="display:flex; height:100%; width:100%; margin:0; padding:0; justify-content:center; align-items:center">
  ...
</div>
</div>
</p>
    </div></answer1>
<exanswer1><div class="answer accepted" i="77784016" l="4.0" c="1704755326" v="1" a="bW9vbg==" ai="22970741">
<p>Upon examination, it seems that the values for both timeElem.offsetWidth and clockElem.offsetWidth remain consistent as you have set timeElem.style.display = 'block'. To potentially address this, I've included a flex style for consideration.</p>
<p><div>
<div>
<pre><code><!DOCTYPE html>
<html lang="en" style="height: 100%;">

<head>
  <title>title</title>
  <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" />


</head>
<style>
  /* Customizable font and colors */
  
  html {
    font-family: 'Courier';
    background: #000000;
    color: #91ff0f;
  }
</style>

<body style="display:flex; height:100%; width:100%; margin:0; padding:0; justify-content:center; align-items:center">
  <div style='height:100%; width: 100%; margin:0 auto'>
    <div id='clockDiv' style='height:60%; width:100%; display:flex; justify-content:center; margin:0 auto'>
      <span id="clocktext" style="font-kerning:none;"></span>
    </div>
    <div id='tempDiv' style='width:100%; margin:0 auto; display:flex; justify-content:center'>
      <span id="temptext" style="font-kerning:none"><:/span>
    </div>
  </div>
  <script>
    // JavaScript functionality here
  </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

Issue encountered when calling theme.breakpoints.down('') function from Material UI

As a novice, I have ventured into using material UI on the front-end of my project. My aim is to achieve responsiveness by leveraging theme.breakpoints.down as indicated in the material UI documentation. However, when attempting to implement this, I encoun ...

Exploring the implementation of `setInterval` within the scope of a particular component in Vue

How can I restrict the scope of setInterval to a specific component only in Quasar framework when using SPA mode? Setting the function causes it to run everywhere, even when the page's URL is changed. I have already checked a similar question on Stac ...

A simple method in JavaScript/TypeScript for converting abbreviations of strings into user-friendly versions for display

Let's say I am receiving data from my backend which can be one of the following: A, B, C, D Although there are actually 20 letters that could be received, and I always know it will be one of these specific letters. For example, I would like to map A ...

Is there a way to initiate an animation by clicking on something?

Currently, I have implemented requestAnimationFrame(loop); and I'm aiming to have an onclick button that triggers the animation. The setup involves clicking a button to initiate the animation process. I have the button structure set up as follows: < ...

Problem with overflow scroll in Internet Explorer 11

I'm working with two ID selectors, 'top' and 'bottom'. The 'top' div has a "position: relative" setting while the 'bottom' div has a fixed position and overlaps the 'top' div. I have also set an "overf ...

Tips for pausing keyframes animation on its final animation frame

Is there a way to halt my animation at the 100% keyframe? What I'm attempting to accomplish is animating these boxes so that when you click on the top one, it moves to the bottom and vice versa. Any suggestions or ideas on how to achieve this? <h ...

How to position the play button in the center using Material UI and Flexbox

Seeking advice on achieving a centered play button with borders in this layout. Struggling with flexbox to position the play button within the code provided. function Tasks(props) { const { classes } = props; return ( <div className={classe ...

How can we ensure only one click event is executed per element type in jQuery?

Here's the issue: I have a list of items with their own content organized in lists. Using jQuery, I've set it up so that when you click on an item, the list expands to show its content. However, when clicking on another item, the previously click ...

Utilizing an Empty Array within an AngularJS Controller Function Invoked by a Directive

I have encountered a tricky issue that appears to be simple, but I am struggling to find a solution. Currently, I am developing a to-do list application using Angular and Angular-Material. The main part of the application is located in a file named main. ...

Steps for creating a new tab and refreshing the address bar with a different URL without having to reload the current page

I'm trying to create a functionality on my page where clicking a button will open a new tab with a modified URL, all without reloading the current page. Below is the code that I'm using when the button is clicked: function changeUrl(){ var pri ...

IE7 disregards the margin set in a div after a div that has been positioned absolutely

Within a container, I have two divs - the first one with absolute positioning. Strangely, in IE7, the second div doesn't seem to acknowledge the top margin. Padding works fine, but for visual consistency, I prefer using margin. The culprit appears to ...

Appear and disappear div

I am seeking to achieve a specific goal: I want to fade in a div with text after a certain number of seconds, then fade it out. I also want to repeat this process for 4 other divs, ensuring that they do not interfere with each other by appearing while the ...

Contrasting the impact of utilizing async:false in conjunction with a callback function versus utilizing jqXHR.done()

According to the jQuery documentation: Starting from jQuery 1.8, using async: false with jqXHR ($.Deferred) is deprecated. Instead, you should utilize the success/error/complete callback options instead of methods like jqXHR.done() or the deprecated jqX ...

Unable to locate module: Unable to locate the file './Header.module.scss' in '/vercel/path0/components/Header'

I encountered an error while attempting to deploy my next application on Vercel. I have thoroughly reviewed my imports, but I am unable to pinpoint the issue. Module not found: Can't resolve './Header.module.scss' in '/vercel/path0/comp ...

Does anyone know how to position div 1 underneath div 2 using CSS?

<div class="1"> <p> THIS IS DIV 1> </p> <div class="2"> <p> THIS IS DIV 2> </p> I'm utilizing a shortcode that seems to consistently appear at the top of all elements. Is there a way to change this behavior? ...

Occasionally, wmuslider fails to load properly

I am currently developing a website for a dance studio and have implemented the wmuslider to create a slider on the homepage. However, I am encountering an issue where the slider does not consistently load. This seems to be a problem across different brows ...

Implementing setInterval in ReactJS to create a countdown timer

I have been working on developing a timer application using React. The functionality involves initiating a setInterval timer when a user clicks a specific button. const [timer, setTimer] = useState(1500) // 25 minutes const [start, setStart] = useState( ...

How can I trigger a function or automate code execution in Angular?

I have some code within a function that is crucial for initializing other variables. The issue I am facing is that this function does not execute unless it is called through another tag in the HTML. Is there a method to automatically initialize this func ...

Establishing limits on the motion of particles

I'm currently using three.js to generate particles and place them in random positions: for( var i = 0; i < particleCount; i++ ){ var pX = Math.random() * 100-50; var pY =Math.random() * 100-50; var pZ = Math.random() * 100-50; particle = n ...

Locate the input field corresponding to a specific label using XPath

I am currently facing a challenge in locating an input box that is positioned adjacent to a label with the text 'Organisation Id'. Since the identification properties of the input box change after every build, I was considering searching for the ...