6

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?

MarksCode
  • 8,074
  • 15
  • 64
  • 133
  • 2
    Two ways to achieve this come to my mind. All with js of course. First you would need to get the parent div width, then you can wrap every word inside a `` tag and iterate them looking at their position until you find the x coordinate bigger than the width. The second method would be to create another `p` element and add letter by letter checking for the width, until de width is bigger than the parent div. – Mark E Jul 10 '17 at 17:51
  • Thanks Mark, I was just implementing your second suggestion. Do you think it's expensive to keep rendering one word at a time and checking the width? – MarksCode Jul 10 '17 at 17:52
  • Don't think so. Unless you were to do this thousands of times. Then you could think of a solution for your problem which doesn't involve looking for that word or change to my first suggestion which would make only one render call. Btw, if you write your function successfully, I would recommend to answer your own question with the function's code to help others with the same problem. – Mark E Jul 10 '17 at 17:58

1 Answers1

4

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.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151