Calculating text width

Jquery

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

This worked better for me:

$.fn.textWidth = function(){
  var html_org = $(this).html();
  var html_calc = '<span>' + html_org + '</span>';
  $(this).html(html_calc);
  var width = $(this).find('span:first').width();
  $(this).html(html_org);
  return width;
};

Solution 2 - Jquery

Here's a function that's better than others posted because

  1. it's shorter
  2. it works when passing an <input>, <span>, or "string".
  3. it's faster for frequent uses because it reuses an existing DOM element.

Demo: http://jsfiddle.net/philfreo/MqM76/

// Calculate width of text from DOM element or string. By Phil Freo <http://philfreo.com>
$.fn.textWidth = function(text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.text(text || this.val() || this.text()).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();
};

Solution 3 - Jquery

My solution

$.fn.textWidth = function(){
    var self = $(this),
        children = self.children(),
        calculator = $('<span style="display: inline-block;" />'),
        width;

    children.wrap(calculator);
    width = children.parent().width(); // parent = the calculator wrapper
    children.unwrap();
    return width;
};

Basically an improvement over Rune's, that doesn't use .html so lightly

Solution 4 - Jquery

The textWidth functions provided in the answers and that accept a string as an argument will not account for leading and trailing white spaces (those are not rendered in the dummy container). Also, they will not work if the text contains any html markup (a sub-string <br> won't produce any output and &nbsp; will return the length of one space).

This is only a problem for the textWidth functions which accept a string, because if a DOM element is given, and .html() is called upon the element, then there is probably no need to fix this for such use case.

But if, for example, you are calculating the width of the text to dynamically modify the width of an text input element as the user types (my current use case), you'll probably want to replace leading and trailing spaces with &nbsp; and encode the string to html.

I used philfreo's solution so here is a version of it that fixes this (with comments on additions):

$.fn.textWidth = function(text, font) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').appendTo(document.body);
    var htmlText = text || this.val() || this.text();
    htmlText = $.fn.textWidth.fakeEl.text(htmlText).html(); //encode to Html
    htmlText = htmlText.replace(/\s/g, "&nbsp;"); //replace trailing and leading spaces
    $.fn.textWidth.fakeEl.html(htmlText).css('font', font || this.css('font'));
    return $.fn.textWidth.fakeEl.width();
};

Solution 5 - Jquery

jQuery's width functions can be a bit shady when trying to determine the text width due to inconsistent box models. The sure way would be to inject div inside your element to determine the actual text width:

$.fn.textWidth = function(){
  var sensor = $('<div />').css({margin: 0, padding: 0});
  $(this).append(sensor);
  var width = sensor.width();
  sensor.remove();
  return width;
};

To use this mini plugin, simply:

$('.calltoaction').textWidth();

Solution 6 - Jquery

I found this solution works well and it inherits the origin font before sizing:

$.fn.textWidth = function(text){
  var org = $(this)
  var html = $('<span style="postion:absolute;width:auto;left:-9999px">' + (text || org.html()) + '</span>');
  if (!text) {
  	html.css("font-family", org.css("font-family"));
  	html.css("font-size", org.css("font-size"));
  }
  $('body').append(html);
  var width = html.width();
  html.remove();
  return width;
}

Solution 7 - Jquery

Neither Rune's nor Brain's was working for me in case when the element that was holding the text had fixed width. I did something similar to Okamera. It uses less selectors.

EDIT: It won't probably work for elements that uses relative font-size, as following code inserts htmlCalc element into body thus looses the information about parents relation.

$.fn.textWidth = function() {
    var htmlCalc = $('<span>' + this.html() + '</span>');
    htmlCalc.css('font-size', this.css('font-size'))
            .hide()
            .prependTo('body');
    var width = htmlCalc.width();
    htmlCalc.remove();
    return width;
};
   

Solution 8 - Jquery

If your trying to do this with text in a select box or if those two arent working try this one instead:

$.fn.textWidth = function(){
 var calc = '<span style="display:none">' + $(this).text() + '</span>';
 $('body').append(calc);
 var width = $('body').find('span:last').width();
 $('body').find('span:last').remove();
 return width;
};

or

function textWidth(text){
 var calc = '<span style="display:none">' + text + '</span>';
 $('body').append(calc);
 var width = $('body').find('span:last').width();
 $('body').find('span:last').remove();
 return width;
};

if you want to grab the text first

Solution 9 - Jquery

the thing, you are doing wrong, that you are calling a method on cTxt, which is a simple string and not a jQuery object. cTxt is really the contained text.

Solution 10 - Jquery

Slight change to Nico's, since .children() will return an empty set if we're referencing a text element like an h1 or p. So we'll use .contents() instead, and use this instead of $(this) since we're creating a method on a jQuery object.

$.fn.textWidth = function(){
    var contents = this.contents(),
        wrapper  = '<span style="display: inline-block;" />',
        width    = '';

    contents.wrapAll(wrapper);
    width = contents.parent().width(); // parent is now the wrapper
    contents.unwrap();
    return width;
    };

Solution 11 - Jquery

after chasing a ghost for two days, trying to figure out why the width of a text was incorrect, i realized it was because of white spaces in the text string that would stop the width calculation.

so, another tip is to check if the whitespaces are causing problems. use

&nbsp;

non-breaking space and see if that fixes it up.

the other functions people suggested work well too, but it was the whitespaces causing trouble.

Solution 12 - Jquery

If you are trying to determine the width of a mix of text nodes and elements inside a given element, you need to wrap all the contents with wrapInner(), calculate the width, and then unwrap the contents.

*Note: You will also need to extend jQuery to add an unwrapInner() function since it is not provided by default.

$.fn.extend({
  unwrapInner: function(selector) {
      return this.each(function() {
          var t = this,
              c = $(t).children(selector);
          if (c.length === 1) {
              c.contents().appendTo(t);
              c.remove();
          }
      });
  },
  textWidth: function() {
    var self = $(this);
    $(this).wrapInner('<span id="text-width-calc"></span>');
    var width = $(this).find('#text-width-calc').width();
    $(this).unwrapInner();
    return width;
  }
});

Solution 13 - Jquery

Expanding on @philfreo's answer:

I've added the ability to check for text-transform, as things like text-transform: uppercase usually tend to make the text wider.

$.fn.textWidth = function (text, font, transform) {
    if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('<span>').hide().appendTo(document.body);
    $.fn.textWidth.fakeEl.text(text || this.val() || this.text())
        .css('font', font || this.css('font'))
        .css('text-transform', transform || this.css('text-transform'));
    return $.fn.textWidth.fakeEl.width();
};

Solution 14 - Jquery

var calc = '<span style="display:none; margin:0 0 0 -999px">' + $('.move').text() + '</span>';

Solution 15 - Jquery

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.

Solution 16 - Jquery

I modified Nico's code to work for my needs.

$.fn.textWidth = function(){
    var self = $(this),
        children = self.contents(),
        calculator = $('<span style="white-space:nowrap;" />'),
        width;

    children.wrap(calculator);
    width = children.parent().width(); // parent = the calculator wrapper
    children.unwrap();
    return width;
};

I'm using .contents() as .children() does not return text nodes which I needed. I also found that the returned width was impacted by the viewport width which was causing wrapping so I'm using white-space:nowrap; to get the correct width regardless of viewport width.

Solution 17 - Jquery

$.fn.textWidth = function(){
        var w = $('body').append($('<span stlye="display:none;" id="textWidth"/>')).find('#textWidth').html($(this).html()[0]).width();
        $('#textWidth').remove();
        console.log(w);
        return w;
    };

almost a one liner. Gives you the with of the first character

Solution 18 - Jquery

I could not get any of the solutions listed to work 100%, so came up with this hybrid, based on ideas from @chmurson (which was in turn based on @Okamera) and also from @philfreo:

(function ($)
{
    var calc;
    $.fn.textWidth = function ()
    {
        // Only create the dummy element once
        calc = calc || $('<span>').css('font', this.css('font')).css({'font-size': this.css('font-size'), display: 'none', 'white-space': 'nowrap' }).appendTo('body');
        var width = calc.html(this.html()).width();
        // Empty out the content until next time - not needed, but cleaner
        calc.empty();
        return width;
    };
})(jQuery);

Notes:

  • this inside a jQuery extension method is already a jQuery object, so no need for all the extra $(this) that many examples have.
  • It only adds the dummy element to the body once, and reuses it.
  • You should also specify white-space: nowrap, just to ensure that it measures it as a single line (and not line wrap based on other page styling).
  • I could not get this to work using font alone and had to explicitly copy font-size as well. Not sure why yet (still investigating).
  • This does not support input fields that way @philfreo does.

Solution 19 - Jquery

Sometimes you also need to measure additionally height and not only text, but also HTML width. I took @philfreo answer and made it more flexbile and useful:

function htmlDimensions(html, font) {
  if (!htmlDimensions.dummyEl) {
    htmlDimensions.dummyEl = $('<div>').hide().appendTo(document.body);
  }
  htmlDimensions.dummyEl.html(html).css('font', font);
  return {
    height: htmlDimensions.dummyEl.height(),
    width: htmlDimensions.dummyEl.width()
  };
}

Solution 20 - Jquery

text width can be different for different parents, for example if u add a text into h1 tag it will be wider than div or label, so my solution like this:

<h1 id="header1">

</h1>

alert(calcTextWidth("bir iki", $("#header1")));

function calcTextWidth(text, parentElem){
	var Elem = $("<label></label>").css("display", "none").text(text);
	parentElem.append(Elem);
  var width = Elem.width();
  Elem.remove();
	return width;
}

Solution 21 - Jquery

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 = '' + $(this).html() + ''; $('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

Solution 22 - Jquery

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDomView Question on Stackoverflow
Solution 1 - JqueryRune KaagaardView Answer on Stackoverflow
Solution 2 - JqueryphilfreoView Answer on Stackoverflow
Solution 3 - JquerybevacquaView Answer on Stackoverflow
Solution 4 - JqueryedsioufiView Answer on Stackoverflow
Solution 5 - JquerybrianreavisView Answer on Stackoverflow
Solution 6 - JqueryVince SpicerView Answer on Stackoverflow
Solution 7 - JquerychmursonView Answer on Stackoverflow
Solution 8 - JqueryokameraView Answer on Stackoverflow
Solution 9 - JqueryJuraj BlahunkaView Answer on Stackoverflow
Solution 10 - Jquery309designerView Answer on Stackoverflow
Solution 11 - JqueryzonabiView Answer on Stackoverflow
Solution 12 - Jquerytrip41View Answer on Stackoverflow
Solution 13 - JqueryshaneparsonsView Answer on Stackoverflow
Solution 14 - JqueryyuraView Answer on Stackoverflow
Solution 15 - JqueryArun Pratap SinghView Answer on Stackoverflow
Solution 16 - Jquerynon_carbondatedView Answer on Stackoverflow
Solution 17 - JqueryceedView Answer on Stackoverflow
Solution 18 - JqueryGone CodingView Answer on Stackoverflow
Solution 19 - JqueryDaniel KmakView Answer on Stackoverflow
Solution 20 - JquerySaeed TaranView Answer on Stackoverflow
Solution 21 - JquerypeetoView Answer on Stackoverflow
Solution 22 - Jqueryuser16662240View Answer on Stackoverflow