Skip to content Skip to sidebar Skip to footer

Get Width Of Last Line In A Paragraph Of Text

Is it possible to somehow measure the length of the last line of text in a paragraph that has multiple breaks / returns? Morbi leo risus, porta ac consectetur ac, vestibu

Solution 1:

It should be sufficient to append a zero-width element at the very end of the string and measure its left offset.

HTML

<p id="text">…text…</p>

JS

// NOTE: This assumes LTR text!
// Using JQuery for simpler code

var $el = $("#text");
var originalText = $el.html();

$el.html(originalText + "<span id='cursor'></span>");
alert($("#cursor").offset().left + "px");
$el.html(originalText);

JSFiddle: http://jsfiddle.net/Ca4fF/1/


Solution 2:

Edit: this was written before the clarification that there are no line breaks in the paragraph. Sorry, not applicable.

If you trim whitespace at beginning and ending of the string (ie the paragraph), and then split around newlines and take the last element of the result, you should be close to getting what you want.

<div class='input'>
Morbi leo risus, porta ac consectetur ac, vestibulum at eros.
Donec id elit non mi porta gravida at eget metus. Nulla vitae
elit libero, a pharetra augue. Nullam id dolor id nibh
ultricies vehicula ut id elit. Vivamus sagittis lacus vel
augue laoreet rutrum faucibus dolor auctor.
</div>
<div class='result'>
</div>

and

$('div.result').html( "" )
$('div.input').each( function(){
    var lines = $(this).html(
       ).replace(/^\s+/, ''
       ).replace(/\s+$/,''
       ).split("\n")
    $('div.result').append("<p><kbd>" + 
       lines[lines.length-1].length + 
       "</kbd>: <i>"+lines[lines.length-1]+"</p>" 
    )       
})

http://jsfiddle.net/xbFAx/


Post a Comment for "Get Width Of Last Line In A Paragraph Of Text"