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?