Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Count visible characters in div

I have a div which contains text (a string of length S) of an arbitrary length, but a fixed size. Beyond a certain length (let's call it L), the text is truncated and the remainder of the text is no longer visible. (Technically speaking, the range [0,L) is visible, the range [L,S) is not).

What I want to do is find the length L for the text by counting only the visible number of characters in the div. Any characters beyond the cut-off point should be disregarded.

I'm happy to use 3rd party libraries like jQuery etc if that will get the job done!

like image 200
Jonathan Ellis Avatar asked Nov 05 '22 02:11

Jonathan Ellis


1 Answers

Here is a function I made for trimming text:

function getTextThatFits(txt, w, fSize, fName, fWeight) {
    if (fWeight === undefined)
        fWeight = "normal";

    var auxDiv = $("<div>").addClass("auxdiv").css ({
        fontFamily : fName,
        fontSize : parseInt(fSize) + "px",
        position: "absolute",
        height: "auto",
        marginLeft : "-1000px",
        marginTop : "-1000px",
        fontWeight: fWeight,
        width: "auto"
    })
    .appendTo($("body"))
    .html(txt);

    var ww = (auxDiv.width() + 1);
    var str = txt;

    if (ww > w)
    {
        var i = 1, p = 1, u = txt.length, sol = 0;

        while (p <= u)
        {
            i = (p + u) >> 1;
            str = txt.slice(0, i);
            auxDiv.html(str);
            ww = (auxDiv.width() + 1);
            if (ww <= w) {
                sol = i;
                p = i + 1;
            }
            else u = i - 1;
        }

        str = txt.slice(0, sol);
    }
    $(".auxdiv").remove();
    auxDiv.remove();
    return str.length;
}

I'm using binary search for finding the text that fits into a specific width. In order to use the function, you must call it like this:

getTextThatFits(yourText, divWidth, fontSize, fontName, fontWeight=optional)
like image 157
gabitzish Avatar answered Nov 07 '22 22:11

gabitzish