Calculating text width

Viewed 124812

I'm trying to calculate text width using jQuery. I'm not sure what, but I am definitely doing something wrong.

So, here is the code:

var c = $('.calltoaction');

var cTxt = c.text();

var cWidth =  cTxt.outerWidth();

c.css('width' , cWidth);
22 Answers

Call getColumnWidth() to get the with of the text. This works perfectly fine.

someFile.css
.columnClass { 
    font-family: Verdana;
    font-size: 11px;
    font-weight: normal;
}


function getColumnWidth(columnClass,text) { 
    tempSpan = $('<span id="tempColumnWidth" class="'+columnClass+'" style="display:none">' + text + '</span>')
          .appendTo($('body'));
    columnWidth = tempSpan.width();
    tempSpan.remove();
return columnWidth;
}

Note:- If you want inline .css pass the font-details in style only.

I had trouble with solutions like @rune-kaagaard's for large amounts of text. I discovered this:

$.fn.textWidth = function() {
 var width = 0;
 var calc = '<span style="display: block; width: 100%; overflow-y: scroll; white-space: nowrap;" class="textwidth"><span>' + $(this).html() + '</span></span>';
 $('body').append(calc);
 var last = $('body').find('span.textwidth:last');
 if (last) {
   var lastcontent = last.find('span');
   width = lastcontent.width();
   last.remove();
 }
 return width;
};

JSFiddle GitHub

If the field is a fixed-width input or contenteditable div, you can get the horizontal scroll width as scrollWidth

      $("input").on("input", function() {
        var width = el[0].scrollWidth;
        
        console.log(width);
      });
Related