Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if text has overflowed [duplicate]

Tags:

javascript

How can you detect if text has overflown? For example, the following text is longer than it's div container allows. How can I detect this in javascript?

<div style="max-width: 100px; white-space:nowrap; overflow: hidden;">     Lorem ipsum dolor sit amet, consectetur adipisicing elit </div> 
like image 672
Brett Avatar asked Jun 20 '11 04:06

Brett


People also ask

How do I use ellipsis text in CSS?

To clip at the transition between characters you can specify text-overflow as an empty string, if that is supported in your target browsers: text-overflow: ''; . This keyword value will display an ellipsis ( '…' , U+2026 HORIZONTAL ELLIPSIS ) to represent clipped text.


2 Answers

If you are using jQuery, you can try comparing the div's width to its scrollWidth.

if ($('#div-id')[0].scrollWidth >  $('#div-id').innerWidth()) {     //Text has over-flown } 
like image 185
Nathan Bell Avatar answered Oct 04 '22 13:10

Nathan Bell


You can detect whether text will fit before you display the element. So you can use this function which doesn't require the element to be on screen.

function textWidth(text, fontProp) {     var tag = document.createElement('div')     tag.style.position = 'absolute'     tag.style.left = '-99in'     tag.style.whiteSpace = 'nowrap'     tag.style.font = fontProp     tag.innerHTML = text      document.body.appendChild(tag)     var result = tag.clientWidth     document.body.removeChild(tag)     return result; } 

Usage:

if (textWidth('Text', 'bold 13px Verdana') > elementWidth) {     ... } 
like image 33
artnikpro Avatar answered Oct 04 '22 13:10

artnikpro