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

What could be the reason my "mandatory" function is not providing any output?

Recently, I've been working on an Express.js application that handles POST requests with a "city" parameter in the body. The application processes this request and utilizes an external service for further operations. To maintain clean code, I separate ...

Eliminating the glow effect, border, and both vertical and horizontal scrollbars from a textarea

Dealing with the textarea element has been a struggle for me. Despite adding decorations, I am still facing issues with it. The glow and border just won't disappear, which is quite frustrating. Could it be because of the form-control class? When I rem ...

"Troubleshooting: Next.js useEffect and useState hooks fail to function properly in a

Working on my project in nextjs, I've implemented the useEffect and useState hooks to fetch data: export default function PricingBlock({ data }) { const [pricingItems, setPricingItems] = useState() const [featuredItem, setFeaturedItem] = useState( ...

Setting up SSL/TLS certificates with Axios and Nest JS

I have a Nest JS application set up to send data from a local service to an online service. However, the requests are not working because we do not have an SSL certificate at the moment. Can anyone provide guidance on configuring Axios in Nest JS to accept ...

The REST API for HTTP DELETE does not validate for null values

Currently facing an issue while developing a RESTful API for a web service. I am attempting to delete an email, but first I need to confirm if the email actually exists. The problem arises when it fails to check if the email is null and does not return a ...

Why does JSON.parse obscure objects in response body when using Node.js?

Whenever I utilize JSON.parse and output some fetched information with the require module, nested objects are shown as [Object]. For example, consider the following code (currently using Node version 10.15): const request = require("request"); const ur ...

AngularJS Object Comparison: A Comprehensive Guide

My form initiates a GET request to the server upon loading, receiving data that is stored in 'master' and then copied to 'local' as shown below. $scope.dirty = false; init(data); function init(data) { $scope.master = angular.copy ...

Error 504: The timeout issue occurred during an ajax call

When I make an ajax call to process a large amount of data and then reload the page upon success, I encounter a 504 Gateway Timeout error. The ajax call is initiated with the following parameters: $.ajax({ type:'POST', cache:false, a ...

What are some ways to stop the default event action from occurring when a parent HTML element has an event handler attached to it?

I have a bunch of hyperlinks on my webpage that I want to ajaxify so that clicking on a link deletes the associated item. I attached an event handler to a parent container like this: <div id="parent"> <a href='#' data-itemid='1& ...

How can the AngularJS model be updated while using long polling with Ajax?

How can I update the model using ajax long polling method? To start, I will load the default list: For example: - id1 - id2 - id3 Next, I set up an ajax long polling process in the background that runs every 5 seconds. When the ajax call receives an upd ...

Error in table layout caused by asynchronous .get jQuery function

I am facing a challenge in populating a timetable with specific information for each cell from a database. The table is being dynamically refreshed using the following function: function refreshTable() { //Form values var park = $('#Park&apos ...

Tips for making an image box with a rollover effect

I need help figuring out how to create a unique user experience within a container that is 500px wide and 800px tall. The container currently has an image as a background, and I want to add a "sign up" button in the middle. When this button is clicked, I w ...

Execute a function (with arguments) within a v-for loop in Vue.js

Currently, I am attempting to create a select element using Vue.js and Material Design that has 2 levels: categories and items. Each category can contain multiple items which may be selected or not. <md-select v-if="categories.length > 0" name="cate ...

Order Up: Vue Draggable Next feature keeps your lists in line

I need to maintain the order of two lists in local storage so that their positions are saved and retrieved between sessions. In my Vue 3 TS project, I am utilizing this library. Check out the code snippet below: <template> <div> <h3> ...

Display a collection of pictures from a directory on a website using JavaScript

I am having trouble displaying a collection of images from a specific folder using JavaScript/jQuery. Below is the code snippet I am working with: $(document).ready(function(){ var dir = "images/"; // specified folder location var fileextension ...

Production Server experiencing issues with sending Large Lists via Http Post

I'm experiencing an issue where the server is unable to read values from a large list when sent using Post. Oddly enough, this works on the homologation server but not on the production server. Http post AngularJs $http({ url: $rootScope.raiz_ws ...

Leveraging the power of angular's $asyncValidators by implementing a cache

I've created a validation directive that verifies a value against an endpoint App.directive('validate', function(fooService, $q) { return { restrict: "A", require: "ngModel", link: function(scope, elem, attrs, ngModel) { ...

Is there a way to pass an HTMLDivElement as a child in React components?

Scenario Currently, I am in the process of developing a React application (rails-react) where the main component is called GameTracker. Within this parent component, there are two child components: EquipmentPanel and PinnedPanels. To achieve a specific fu ...

Enhancing Bootstrap Slider Range with jQuery/Javascript

Currently, I have incorporated the Bootstrap slider into a webpage that features two sliders on a single page. The range of the second slider depends on the value of the first one. It is crucial for me to be able to update the range of the second slider af ...

Creating a table with merged (colspan or rowspan) cells in HTML

Looking for assistance in creating an HTML table with a specific structure. Any help is appreciated! Thank you! https://i.stack.imgur.com/GVfhs.png Edit : [[Added the headers to table]].We need to develop this table within an Angular 9 application using T ...