user1418419
user1418419

Reputation:

JQuery find the length of string that div can contain

I have a Div, which dosn't have fix height or width. the div will contain some text, the length of string not fix. if the String is too long to fit in the div, the text will appear outside the div, what I need is to know how much maximum length of String the div can contain based on it's width and height.

Upvotes: 3

Views: 4935

Answers (4)

jfriend00
jfriend00

Reputation: 707786

Unless you are using a fixed width font where all characters are the same width (which is unusual), there is no answer to your question. How many characters fit in a given width depends upon what the characters are as characters like a "W" are much wider than characters like an "i" in all variable width fonts.

If you are using a fixed width font, then you need to measure how wide a character is in the font and font-size and font-style you're using. You can then simply divide the width you have by the character width and determine how many characters will fit.

It is possible to measure a fixed width font, by creating a div with no margin, padding or border, setting the style to position: absolute, setting the desired font-family and font-size on it and putting one character in the div. You can then fetch the width of the div by getting it's offsetWidth.

See http://jsfiddle.net/jfriend00/kHHU7/ for a simple example.

Here's a function that measure's the width of a character in a fixed width font:

function getCharWidth(fontFamily, fontSize) {
    var div = document.createElement("div");
    div.style.position = "absolute";
    div.style.visibility = "hidden";
    div.style.fontFamily = fontFamily;
    div.style.fontSize = fontSize;
    div.innerHTML = "S";
    document.body.appendChild(div);
    var width = div.offsetWidth;
    document.body.removeChild(div);
    return(width);
}

You can see it work here: http://jsfiddle.net/jfriend00/y4eZr/

Upvotes: 4

Muhd
Muhd

Reputation: 25606

I would check out the jQuery plugin dotdotdot for handling this. You don't need to know how long, it will do all the work for you of truncating the text to the appropriate length.

Upvotes: 1

Sergei Zahharenko
Sergei Zahharenko

Reputation: 1524

maybe it's better to use css overflow:hidden on div?

Upvotes: 1

Jeffrey Sweeney
Jeffrey Sweeney

Reputation: 6124

Divider elements are fluid container elements and aren't really designed to do this sort of thing.

The best way I can think of to achieve this is divide the clientWidth of the div by the presumed font width.

var maxChars = div.clientWidth / 5;

Upvotes: 0

Related Questions