Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knowing how wide a text line will be in HTML for word wrap and other applications

Do you know a good cross-browser way of knowing how wide will be a text line so you can break it exactly to fit a fixed width?

Suppose you want to break a long text like so it doesn't overflow a fixed width container, but you want the line to break the closest to the border possible, so guessing where to insert ­s isn't a clean solution.

I want to investigate, I imagine this could be done having an invisible div then printing the line inside it and checking the div's width, or something like that, with Javascript.

Has anyone done something like this?

*(the focus is not word wrapping, that's just the application that comes to my mind now, but knowing a text's width is what I want)

like image 795
Petruza Avatar asked Nov 05 '22 20:11

Petruza


1 Answers

Here is a complete "Heath Robinson" (does that reference travel well?) approach.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <script type="text/javascript">
        function txtContent_onchange()
        {
            var span = document.getElementById("spanMeasure")
            span.innerHTML = "";
            span.appendChild(document.createTextNode(this.value));
            document.getElementById("txtWidth").value = span.scrollWidth;

        }
    </script>
    <style type="text/css">
        #spanMeasure 
        {
            position:absolute;
            top:0px;
            left:0px;
            visibility:hidden;
            width:10px;
            white-space:nowrap;
            overflow:hidden
        }
    </style>
</head>
<body>

    <input id="txtContent" onchange="txtContent_onchange.call(this)" /><br />
    <input id="txtWidth" />
    <span id="spanMeasure"><span>

</body>
</html>

The critical thing here is the configuration of the span element. This element will not impact the visual appearance of the page. Its scrollWidth property will return the length of the text it contains. Of course you would need to set any font style attributes to get a reasonable value.

According to quirksmode site Opera may be a little flaky with this approach but I suspect its the closest you will get to a fully cross-browser solution.

like image 67
AnthonyWJones Avatar answered Nov 12 '22 16:11

AnthonyWJones