Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <code>textWidth</code> functions provided in the answers and that accept a <code>string</code> 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 <code>&lt;br&gt;</code> won't produce any output and <code>&amp;nbsp;</code> will return the length of one space).</p> <p>This is only a problem for the <code>textWidth</code> functions which accept a <code>string</code>, because if a DOM element is given, and <code>.html()</code> is called upon the element, then there is probably no need to fix this for such use case.</p> <p>But if, for example, you are calculating the width of the text to dynamically modify the width of an text <code>input</code> element as the user types (my current use case), you'll probably want to replace leading and trailing spaces with <code>&amp;nbsp;</code> and encode the string to html.</p> <p>I used philfreo's solution so here is a version of it that fixes this (with comments on additions):</p> <pre><code>$.fn.textWidth = function(text, font) { if (!$.fn.textWidth.fakeEl) $.fn.textWidth.fakeEl = $('&lt;span&gt;').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, "&amp;nbsp;"); //replace trailing and leading spaces $.fn.textWidth.fakeEl.html(htmlText).css('font', font || this.css('font')); return $.fn.textWidth.fakeEl.width(); }; </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload