Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect word the causes overflow

Tags:

I have a <p> tag inside a <div> which I've set the following properties on:

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

If the <p> tag contains a lot of text then some of it will be cut off.

My goal is to detect what the first word not being shown is.

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 would return the word "explode".

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

like image 566
MarksCode Avatar asked Jul 10 '17 17:07

MarksCode


People also ask

What causes overflow CSS?

Overflow happens when there is too much content to fit in a box. CSS provides various tools to manage overflow. As you go further with CSS layout and writing CSS, you will encounter more overflow situations.

What is element overflow?

The overflow property specifies whether to clip the content or to add scrollbars when the content of an element is too big to fit in the specified area. The overflow property has the following values: visible - Default. The overflow is not clipped. The content renders outside the element's box.


1 Answers

After multiple approaches i think the easiest is adding one word after another, 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 may actually improve rendering spead later as all overflowing content is never added again.

like image 96
Jonas Wilms Avatar answered Sep 30 '22 15:09

Jonas Wilms