Detect if text has overflowed
JavascriptJavascript Problem Overview
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>
Javascript Solutions
Solution 1 - Javascript
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
}
Solution 2 - Javascript
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) {
...
}
Solution 3 - Javascript
jQuery plugin for checking if text has overflown, not written very well, but works as it suppose to be working. Posting this because I didn't find a working plugin for this anywhere.
jQuery.fn.hasOverflown = function () {
var res;
var cont = $('<div>'+this.text()+'</div>').css("display", "table")
.css("z-index", "-1").css("position", "absolute")
.css("font-family", this.css("font-family"))
.css("font-size", this.css("font-size"))
.css("font-weight", this.css("font-weight")).appendTo('body');
res = (cont.width()>this.width());
cont.remove();
return res;
}
Solution 4 - Javascript
For illustrative purposes let's say your div has id="d"
, then you could do:
var d = document.getElementById('d'),
dWider;
d.style.maxWidth = '9999em';
d.style.overflow = 'visible';
dWider = d.offsetWidth > 100;
d.style.maxWidth = '100px';
d.style.overflow = 'hidden';
Then the var dWider
will be true if the text overflows and false if it doesn't.