How can we enhance the efficiency of rendering text on the screen?

Imagine having a <p> tag inside a <div> with specific properties:

div {
   height: 100px;
   width: 100px;
   overflow: hidden;
}

My goal is to continuously add words to the <p> tag until an overflow is detected, meaning stop when the first word that doesn't fit is added.

This is achieved through the following code snippet:

var textToRender = "People assume I'm a boiler ready to explode, but I actually have very low blood pressure, which is shocking to people.";
var words = textToRender.split(" ");

var div = document.getElementById("mydiv");
var p = document.getElementById("myp");

var i = 0;
while (p.clientHeight <= div.clientHeight && i<words.length) {
  p.textContent += words[i++] + ' ';
};
div {
  height: 55px;
  width: 200px;
  overflow: hidden;
}
<div id="mydiv">
  <p id="myp"></p>
</div>

Now imagine scaling this up significantly by handling 50 divs of varying sizes and texts. To further optimize this process without prior knowledge of line-height, container div height, or word count, here's my question: Would placing an opaque <div> on top of the container during the word-by-word drawing process, then removing it post-overflow detection enhance performance since the actual words wouldn't render in each iteration of the while loop?

If not, are there alternative strategies that could be employed to streamline this operation?

Answer №1

Consider implementing the binary search algorithm for optimal results.

let textToProcess = "She thought she could, so she did.";
let wordsArray = textToProcess.split(" ");

let mainDiv = document.getElementById("main-content");
let paragraph = document.createElement("p");

let left = 0, right = wordsArray.length, middle;
while (left < right) {
  middle = Math.floor((left + right) / 2);
  paragraph.textContent = wordsArray.slice(0, middle).join(' ');
  if (paragraph.clientHeight <= mainDiv.clientHeight /* consider adding extra line height */) 
    left = middle + 1; 
  else 
    right = middle - 1;
}
paragraph.textContent = wordsArray.slice(0, left + 1).join(' ');
div {
  height: 55px;
  width: 200px;
  overflow: hidden;
}
<div id="main-content">
  <p></p>
</div>

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

Strategies for transferring information to a different component in a React application

Building a movie site where users can search for films, click on a card, and access more details about the film is proving challenging. The problem lies in transferring the film details to the dedicated details page once the user clicks on the card. An onc ...

Is there a way to use a single url in Angular for all routing purposes

My app's main page is accessed through this url: http://localhost:4200/ Every time the user clicks on a next button, a new screen is loaded with a different url pattern, examples of which are shown below: http://localhost:4200/screen/static/text/1/0 ...

Updating the redux state in react by passing a variable from a child component to the parent

I'm currently in the process of updating my Redux state within a component by utilizing a variable that has been passed up to the component from a child, specifically through a form submission callback. The form is responsible for submitting a user&ap ...

Steps to have the initial link redirect to a designated webpage

I am working with tables that have links defined in the HTML. I want to modify the behavior so that the first link opens a different URL, for example: john.com. Is it possible to achieve this? Specifically, I want the link associated with the first name ( ...

problems encountered when including next.config.js for sitemap creation in a nextjs application

Just recently, I made an update to my next.config.json file in hopes of boosting SEO performance. However, this change has caused some issues with the next-sitemap module, preventing me from building or starting my app. //next.config.js const withSitemap = ...

Converting JSON formatting from Object to Array: A Comprehensive Guide

Encountering another issue with changing the JSON array output. Struggling to figure out why it's not rendering the other files. Providing a clearer explanation below: In my code snippet, when I use data[name] = {, each return name is rendered into ...

What is the best way to link labels with input fields located separately in Angular?

Imagine a scenario where labels and form fields are being created in a *ngFor loop, as shown below: app.component.ts export class AppComponent { items = ['aaa', 'bbbbbb', 'ccccccccc'] } app.component.html <div class ...

Can we display an express view in response to a WebSocket event?

My goal is to display an express view within a websocket event as shown below: socket.on('name', function () { //prompt the client to render a specific express view }); ...

Unable to retrieve /ID from querystring using Express and nodeJS

I am brand new to the world of Express and nodeJS. I have been experimenting with query strings and dynamic web pages, but I keep getting an error saying that it cannot retrieve the ID. I'm completely lost as to where I might have made a mistake. An ...

The error message "TypeError: res.response is undefined" is indicating

Currently, I am implementing user authentication using JWT auth within a Vue/Laravel single-page application. The problem arises in the register module as it fails to respond upon clicking the button. Upon inspecting the Firefox developer edition's co ...

"Sweet syntax" for assigning object property if the value is true

In the project I'm working on, I find myself dealing with a lot of parsing and validating tasks. This often results in 5-10+ lines of code like if(value) object.value = value. I considered using object.value = value || (your favorite falsy value) app ...

What is the functionality of this.$eval in Vue.js?

During the process of updating an unfamiliar old script from version 0.11 to 2.5.4, an alert popped up stating: To address the warning message saying 'Replace this.$eval('reportData | reportFilter false') with a solution using normal Java ...

The functionality of ngModel is not functioning properly on a modal page within Ionic version 6

Currently I am working on an Ionic/Angular application and I have encountered a situation where I am attempting to utilize ngModel. Essentially, I am trying to implement the following functionality within my app: <ion-list> <ion-item> <ion ...

The choices in the second dropdown menu will change based on the selection made in the first dropdown menu

Currently utilizing reactJS, I have the choices for two dropdown lists named categories and items. constructor(props) { super(props) } this.state = { categories: [ { "id": 1, "category_name": ...

Error in AngularJS v1.2.5 when using textarea with placeholder attribute in IE11

Having trouble with an Angular JS v1.2.5 form that is not functioning in IE11, despite working perfectly in Firefox, Chrome, and Safari. The issue seems to be related to using interpolation inside the placeholder attribute of a textarea. <body ng-con ...

Is it possible to customize the pagination-control labels from numbers (1 2 3) to different values, such as 'Anything1 Anything2 ...', by utilizing ngFor* with an array in ngx-pagination?

Is there a way to customize ngx-pagination's pagination control? Currently, the page numbers are displayed as '1 2 3' but I would like to replace them with specific string values from an array. <pagination-controls (pageChange)=& ...

Sending a JavaScript variable to a Ruby on Rails controller for passing it to an API for further processing

My index.html file contains a Google API map implementation. <!DOCTYPE html> <html> <head> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> html, body { height: ...

The link tag cannot be used inside a division element

I am facing an issue with a button that has three different states represented by images. While the button looks great and functions well, it fails to perform its primary function - linking to another document. Upon clicking the button, no action is initi ...

The jQuery Multiselect filter contradicts the functionality of single select feature

http://jsfiddle.net/rH2K6/ <-- The Single Select feature is functioning correctly in this example. $("select").multiselect({ multiple: false, click: function(event, ui){ } http://jsfiddle.net/d3CLM/ <-- The Single Select breaks down in this sc ...

The routing navigate method is failing to direct to the desired component

For the past day, I have been struggling to find a solution to my issue but without success. The routing seems to be malfunctioning as it keeps showing the HTML content from app.component.html even when I try changing the path in the URL. Here is a snippe ...