Detect word overflow

I have a <p> inside a <div> that I set the following properties for:

 div { height: 105px; width: 60px; overflow: hidden; } 

If the <p> contains a lot of text, some of them will be truncated.

My goal is to find that the first word is not displayed.

For example, in the following scenario:

 div { height: 105px; width: 60px; overflow: hidden; } 
 <div> <p>People assume I'm a boiler ready to explode, but I actually have very low blood pressure, which is shocking to people.</p> </div> 

the function will return the word "explode".

I know from this question that it is quite easy to detect if there is an overflow, but can we take this step further and determine which word is the first to be hidden?

+5
javascript html css
source share
1 answer

After several approaches, I think the easiest way is to add one word after another, and then check if the paragraph overflows:

 window.onload=function(){ var el=document.getElementById("el"); var words=el.textContent.split(" "); el.textContent=""; var thatword=words.find(function(word,i){ el.textContent+=(i?" ":"")+word; //console.log(el.clientWidth,el.scrollWidth,el.clientHeight,el.scrollHeight); return el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight; }); alert(thatword); }; 
 #el { height: 105px; width: 60px; overflow: hidden; } 
 <div> <p id="el">People assume I'm a boiler ready to explode, but I actually have very low blood pressure, which is shocking to people.</p> </div> 

This can actually improve spead rendering later, since all overflowing content is no longer added.

+4
source share

All Articles