Detect if text has overflowed [duplicate]

Solution 1:

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:

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:

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;
}