Adjust the font size based on the dimensions of the container

I'm currently working on a script that dynamically sets the font-size based on the container's dimensions and the length of the text.

This is what I have implemented so far.

    window.onload = function () {
    var defaultDimensions = 300;
    var boxWidth = window.innerWidth / Math.floor(window.innerWidth / defaultDimensions);
    var boxes = document.getElementsByClassName('feed');
    for (var i = 0; i < boxes.length; i++) {
        boxes[i].style.width = boxWidth + 'px';
        boxes[i].style.height = boxWidth + 'px';
    }
};
var getFontSizeStatus = function (text) {
    var chars = 250; // Maximum Characters
    var height = 300; // Default Height
    if (text.length < chars) {
        chars = text.length;
    }
    if ((window.innerWidth / Math.floor(window.innerWidth / height)) < height) {
        height = window.innerWidth / Math.floor(window.innerWidth / height);
    }
    height = (height / 10) * 8; // .feed-text height is 80% of .feed's height

    var size = height / chars;
    return size + 'em';
}

You can find the full code on this fiddle link.

The current implementation is functional, but some adjustments are needed to ensure the font-size aligns better with the container's dimensions and text lengths.

Answer №1

One potential solution could be utilizing a jQuery plugin such as fitText

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

Steps to create a toggle feature for the FAQ accordion

I am currently working on creating an interactive FAQ accordion with specific features in mind: 1- Only one question and answer visible at a time (I have achieved this) 2- When toggling the open question, it should close automatically (having trouble with ...

"Here's a neat trick for assigning the value of a div to a text box without any identifiers like id or

I needed a way to transfer the value of a .item div into an empty textbox without any specific identifier. Then, when the input loses focus, the value should be sent back to the original .item div. $(document).on("click", ".item", function() { $(this) ...

Creating an HTML Canvas using an AngularJS template

I am facing an issue with rendering html elements on a canvas using html2canvas JS. I am utilizing AngularJS for data binding on the html page, but unfortunately, the dynamic data is not showing up on the canvas generated from these html elements. For inst ...

pnpm may not be able to resolve dependencies

When I have my package.json file and install all dependencies with npm i, everything works fine. However, when I use pnpm i, I encounter an exception: TypeError: Cannot read property 'uid' of undefined. I don't actually use this library, so ...

Struggle with registering fonts in Canvas using JavaScript

I've been struggling to add a custom font to my canvas for hosting the bot. Even though I'm not encountering any errors, the font fails to display on the host. Below is the code snippet: const { AttachmentBuilder } = require('discord.js&apos ...

Unveiling the secrets to integrating real-time graphical representations of sensor

I have successfully connected a temperature sensor to the BeagleBone Black [BBB] board. Every 1 second, the sensor senses the temperature and passes it to the BBB. The BeagleBone then dumps this data into a MySQL database on another computer. Now, I want t ...

Utilizing a combination of MVC, jQuery, and Ajax to ensure that JavaScript is fully loaded before proceeding

Utilizing ASP.NET MVC and jQuery, I am loading a PartialView via Ajax which has its own accompanying JavaScript file. Upon successful retrieval of the html content, it is inserted into the DOM. However, there can be a delay between the insertion and the ex ...

"My JavaScript code for toggling visibility is not functioning properly. Any suggestions on how to fix

I am currently working on a task that involves showing and hiding container1, but I am confused as to why my code is not functioning properly. The task requirements are as follows: - Clicking on the "Show" button should display container1 - Clicking on the ...

How can I add content using HTML or JavaScript?

How can I append a .txt file using HTML or Java without ActiveX prompts getting in the way? It's becoming quite annoying! Is there a simple way to script this task without having to deal with ActiveX? The current script snippet looks something like ...

How to Enhance GraphQL Mutation OutputFields with a Function Generator

I'm encountering issues while trying to incorporate a function generator within a GraphQL mutation. The function generator is utilized to streamline the promise chain inside the mutation. Prior to refactoring the code, everything was functioning corr ...

Is there a way to access the history of Vue routers?

I am looking for a way to determine if the Vue router has additional entries in its history that can be navigated back to. This information is crucial for deciding whether or not to execute the exit app function. The app should only navigate back to prev ...

What is the method for obtaining the viewModel in a Knockout component?

I need to prepopulate a knockout component when the document is ready. This is the code I have written: function Finding(id, trigger) { var self = this; self.id = ko.observable(id); self.trigger = ko.observable(trigger); } function FindingVi ...

Can someone help me figure out how to increase the values of two specific attributes within a class?

Currently facing a challenge with adjusting the number of likes and comments using increment for properties 'numberOfLikes' and 'comments'. Unsure whether to utilize a for loop or just the increment operator. Still new to coding, so apo ...

Every time I attempt to execute this piece of code in "node.js", an error pops up

const express = require('express'); const request = require('request'); const bodyParser = require('body-parser'); const https = require('https'); const app = express(); app.use(express.static('public')); ...

Calculating the total of an array's values using JavaScript

Receiving information from an API and looking to aggregate the values it contains. Consider the following code snippet: function totalPesos(){ $http.get('/api/valueForTest') .then(function(data){ $scope.resumePesos = data.data.Re ...

Angular does not display a loading indicator in the header

When handling service calls, I have implemented a loading indicator to provide feedback to the user. However, it appears that this indicator is not effectively preventing users from interacting with header items before the loading process is complete. My ...

Efficiently process 100 tasks per minute using a microservice architecture

I have a node.js application that needs to perform the following tasks: Retrieve zip files, extract them (containing JS module files with key-value pairs - usually 5-8 files per request) Analyze these files, create new ones from the analysis, and ...

The downside Div is being displaced by a Paragraph with an overflow-y:scroll property

In my Div, I have set the width and height of a paragraph along with the property overflow-y:scroll. It's working fine as the paragraph is displaying with a vertical scroll. However, it is causing displacement in the div below. Below is the HTML code ...

React function does not provide a return value

In my function, I am calculating the current sum of elements. Within my Api, there is a method called Getcoin that works correctly when I log each element during the foreach cycle. However, I am not getting any results in the return statement or console.lo ...

Move a sub-division horizontally within a parent element that has a full width of 100%

I am currently incorporating some jQuery features into my website. The concept involves expanding the parent div to 100% width for responsive design as you scroll down the page, which works perfectly. Simultaneously, I aim to translateX the child div so th ...