PicoCreator
PicoCreator

Reputation: 10154

Javascript : getting the display width of text string in a pre container, in em

Add non monospace font, tab space in container, etc...

So how does one derive the width of a text string to be displayed in the container... in em (not px).

This can be useful on devices / website that change the font often. Hence there is no need to "redraw" the size (using the insert, measure, remove) method on every re-size. Some of which has no event to trigger/watch.

Manually using em work so far... the problem is making it automatic. As even jQuery.width() returns its result in px.

Upvotes: 1

Views: 617

Answers (2)

PicoCreator
PicoCreator

Reputation: 10154

Not perfect, but gets the job done (somewhat) [uses jQuery]

// [div] : a dom node to test insertion of string (inherits its css prop too)
// [str] : the string to test against
function getEmLen( div, str ) {
    var oriInner = div.innerHTML;
    var res;

    div.innerHTML = '<a>'+str+'</a><a>m</a>';

    res = Math.ceil( 100 * (jQuery(div.firstChild).width()) / (jQuery(div.lastChild).width()) ) / 100; 
    //the * 100, / 100 is to remove long trailing divides

    div.innerHTML = oriInner;
    return ''+res+'em';
}

Upvotes: 0

Aadit M Shah
Aadit M Shah

Reputation: 74204

You can convert px into em. Remember the formula:

var em = px / fontSize;

So, if you have a pre element with the font-size set as 1em which is usually 16px, and your width in px is say 800px, then your width in em is 800 / 16 or 50em. Hope that helps. Vote for my answer if you found it useful.

Upvotes: 2

Related Questions