Ways to enable the font size to dynamically adapt to a div's dimensions

Is dealing with the following scenario:

I am currently working on a component that will handle text and my requirement is to implement automatic size adjustment based on the text length.

For example, if the content has a width of 50px, once the text reaches this limit, the font size should automatically decrease.

I've managed to create a structure that works perfectly for a single component call. However, when I make multiple calls to it, the settings for the first texts get lost, leaving only the correct configuration for the last text.

How can I resolve this issue?

Is there a way to address this using CSS/JS?

Could using Vue be a solution, possibly by destroying the instance with each call? How would I go about doing this?

Below is the code snippet:

Parent

<template>
  <div>
    <div id="content" v-if="this.text != null && this.text != ''">
      <span>
        {{ this.resizeText(this.text) }}
      </span>
    </div>
  </div>
</template>

<script>
export default {
  props: ["text"],

  methods: {
    resizeText(text) {
      $(document).ready(function () {
        $("#content").textfill({
          maxFontPixels: 25,
        });
      });
      return this.text;
    },
  },
};
</script>

<style>
#content {
  border: 1px solid red;
  height: 50px;
  width: 300px;
}
</style>

Children

<template>
  <div class="content-example">
      
    <gui-text-test
      :text="'APPLIED CORRECTLY APPLIED CORRECTLY  '"
    ></gui-text-test>

    <br>

    <gui-text-test
      :text="'DID NOT WORK DID NOT  '"
    ></gui-text-test>

    <br>

    <gui-text-test
      :text="'DID NOT WORK DID NOT WORK DID NOT WORK DID NOT WORK DID NOT WORK '"
    ></gui-text-test>

  </div>
</template>

<script>

import Text2 from '../Text/Text2.vue';

export default {
    components:{
        'gui-text-test': Text2
    }
}

</script>

<style>

</style>

Snippet

$(document).ready(function() {
    $('#conteudo').textfill({
        maxFontPixels: 25
    });
});
#conteudo {
    width: 300px;
    height: 300px;
    border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://jquery-textfill.github.io/js/textfill/jquery.textfill.js"></script>

<div id="conteudo">
    <span>
    <!-- type more data here !-->
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </span>
   
</div>

<div id="conteudo">
    <span>
    <!-- type more data here !-->
        Lorem ipsum dolor sit amet, consectetur adipiscing elit.
    </span>
   
</div>

To test, just add more words in both content 1 and content 2. Notice how one works correctly.

Answer №1

Your issue stems from the use of an id (which should be unique within your document) instead of a class (which can be used multiple times).

id

The id global attribute establishes an identifier (ID) that must be unique throughout the entire document. Its purpose is to uniquely identify the element for referencing (through fragment identifiers), scripting, or styling (with CSS).

Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id

class

The class global attribute represents a list of case-sensitive classes assigned to the element. Classes enable CSS and JavaScript to target and manipulate specific elements using class selectors or methods like document.getElementsByClassName in the DOM.

Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/class

In this code snippet, I've made the following updates:

  • Changed the HTML attribute from id to class
  • Revised the jQuery selector from selecting by id to a class selector
  • Adjusted the CSS selector from targeting ids to using a class selector.

$(document).ready(function() {
    $('.conteudo').textfill({
        maxFontPixels: 25
    });
});
.conteudo {
    width: 300px;
    height: 300px;
    border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://jquery-textfill.github.io/js/textfill/jquery.textfill.js"></script>

<div class="conteudo">
    <span>
    <!-- type more data here !-->
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
    </span>
   
</div>

<div class="conteudo">
    <span>
    <!-- type more data here !-->
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
    </span>
   
</div>

Answer №2

It is important to avoid using the same id for multiple elements as it is not HTML valid and can cause issues when using JavaScript. It will only affect one element instead of all instances. Consider replacing your id with a class and running the method on the class instead. @Stanislas provided a great example solution.

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

The error message "Uncaught TypeError: Cannot read property 'createDocumentFragment' of null" occurs when using Jquery in Django

Struggling to identify the issue with this code that was previously functioning but started malfunctioning after reorganizing the JavaScript at the bottom of the page. It keeps throwing this error: https://i.sstatic.net/fozqo.jpg The line triggering the e ...

Tips for automatically focusing a div upon page load

Here is a code snippet for you to review: <div id="details"> <nav> <a href="#1"><span>Summary</span></a> <a href="#2"><span>Perso ...

Using cytoscape.js to implement a distinct color mapping for node background colors

I am currently learning Javascript and Cytoscape.JS, and I am attempting to implement a discrete color mapping for my nodes based on a specific property in my data. This property consists of five unique values (a, b, c, d, e), and I want to assign colors t ...

XHR object encountered a 404 error while attempting a GET request with an unknown URI component name

Currently, I am attempting to design a text box that triggers a server query as soon as a character is entered into it. However, I am encountering an error message that is puzzling me: Traceback (most recent call last): File "/Users/sahandzarrinkoub/Do ...

Troubleshooting problem with Webpack and TypeScript (ts-loader)

Seeking help to configure SolidJS with Webpack and ts-loader. Encountering an issue with return functions. What specific settings are needed in the loader to resolve this problem? import { render } from "solid-js/web"; const App = () => { ...

How to effectively filter a JSON array using multiple keys?

I need help filtering my JSON data by finding the objects with key 'status' equal to 'p' within the lease array. I attempted to use the following function, but it did not achieve the desired result: myActiveContractItems.filter((myActiv ...

Is there a way to utilize JavaScript or jQuery to modify the background color of the `Save` and `Cancel` buttons within a SharePoint 2013 edit form?

Is there a way to modify the background color of the Save and Cancel buttons on a SharePoint 2013 edit form using JavaScript or jQuery? ...

Constantly being redirected to error page by Vue router

I've been working on setting up a redirect for when the user is not logged in. However, I seem to be encountering an issue where the URL changes but I receive a "This page could not be found" error from Nuxt. The code I'm using is located in a fi ...

Update the Parent CRM Page upon closing the child ASP.net page

This pertains to CRM 2016 on-premise implementation. In my CRM 2016 environment, I have a customized button in the command bar that utilizes a JavaScript web resource to invoke an external asp.net page hosted on another server. This external page facilita ...

I'm struggling to center my navigation bar and adjust its size properly, causing the page to overflow

I am facing some issues with my navigation bar. I am unable to adjust its size or position it at the center of the page. Additionally, despite setting the body width and height to 100vw and 100vh respectively, I am able to scroll both vertically and horizo ...

Tips for connecting lines between md-radio-buttons housed in a div with a label using Angular Materials

I am looking to enhance my md-radio-buttons by adding connecting lines between them in a component that uses dynamic data. <md-radio-group ng-model="selected" layout="row"> <div ng-repeat="i in items"> <label>{{i.name}}</labe ...

Styling the Bootstrap Side Navigation Bar for Desktop View

My bootstrap navbar has a unique feature where the menu slides out from the right when clicked on mobile and small viewports. However, I want it to display the standard bootstrap styles for the desktop version (no menu button, just inline menu items in t ...

Converting a Selenium By object into a CSS selector: A step-by-step guide

When working with Selenium WebDriver, it's a common practice to find elements using the By class. Currently, I'm using a ByChained selector and I'm curious if there's a way to convert a By object to a CSS selector. For instance: By sel ...

Getting the value of the chosen option from one component and passing it to another component in Angular 8

How can I pass the selected option value from the login component to the home component without using local storage? When an option is selected in the login component, I want that value to be displayed in the home component. Below is the code snippet: Lo ...

Adding an HTML string to the head in Next.js

Every time I fetch data from an API, it returns an object with the property head: '<title>dummy title<title>' Despite trying different methods, I am unable to display this HTML string in the head tag. This is my code: <Head>{da ...

What is the reason for the || operator failing to function properly in JavaScript?

In my Node.js and Express pagination setup, I encountered an issue where if the slug <= 0, it would not default to 1. new(req, res, next) { let perPage = 16; //let page = req.params.page <= 0 ? 1: req.params.page; //This works ...

Posting files to Google Cloud Buckets via the REST API

I've been searching everywhere but haven't found a solution to my problem. I'm attempting to upload a file to a Google Cloud bucket within my project using REST APIs, however, all I seem to get is a binary file in the bucket instead of the a ...

Introducing an exception to every jQuery post() method

Our app utilizes AJAX with jQuery to manage user information. We determine the success or failure of an API call by checking data.success or data.error respectively. Additionally, we implement the jQuery error() function in each post() method to handle any ...

What category does React.js fall under - library or framework?

Hey there! I've noticed that sometimes people refer to React JS as a library, while others call it a framework. Can you shed some light on which term is more accurate? ...

Using FlexBox for Vertical Alignment of Elements

Experimenting with FlexBox (for demonstration purposes only). I am facing a challenge in vertically centering text within the parent .top-nav-bar. While using justify-content: space-between, I have successfully aligned two elements horizontally, but I am s ...