1

I am trying to figure out how to calculate just the width of one line of text with jquery.

I have the following text in an string

"Line 1

Line 2

Line 3

Line 4 Blah

Line 5"

When testing to find the width of the text which is shown on the page it always shows 77 px from where line 4 is the longest.

The text is put in using Jquery command .append() on the element id #text

the code used for the element is

<div id = 'terminal'><pre><span id = 'text'></span></pre>

How would I calculate just the width of Line 5?

Thanks - Ryan

Ryan Walmsley
  • 369
  • 1
  • 4
  • 18

5 Answers5

2
$(function(){
  var text =  $.trim($('#demo').text());
  // this may vary browser to browser...
  var text_w_no_empty_lines = text.replace(/[\r\n]+/g, '\n');
  var lines = text_w_no_empty_lines.split('\n');
  // line number you want  total - 1
  var line_5 = lines[4];
  // .tick { white-space:nowrap;display:inline-block;display:none }
  alert( $('<p class="tick">').html(line_5).appendTo('body').width() )
});

        <p id="demo" style="white-space:pre">
        Line 1

        Line 2

        Line 3

        Line 4 Blah

        Line 5
        </p>
  • NOTE: the trick here is to use css white-space:pre to mantain the real height and pre style
Luca Filosofi
  • 30,905
  • 9
  • 70
  • 77
0

Put the strings in multiple div elements and use .width() on the 5th.

benweet
  • 3,685
  • 1
  • 21
  • 26
0

You can append your text to a div with width:auto, and take that div's width.

something like this:

var auxDiv = $("<div>").css({width : "auto"}).appendTo($("body")).html("<div id = 'terminal'><pre><span id = 'text'></span></pre>");

var widthOfText = auxDiv.width();
auxDiv.remove();
gabitzish
  • 9,535
  • 7
  • 44
  • 65
0

HTML:

<style>.temp{display:none}</style>
​<pre class="preview"></pre>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
​<span class="temp"></span>

JS:

$(document).ready(function(){

    var string = 'line 1\nline 2 ... \nline 3..',
        lines = string.split('\n'),
        $temp = $('.temp').show();

    $('.preview').html(string);

    $.each(lines, function(key, str) {
        console.log(key + ': ' + $temp.html(str).width())
    })
    $temp.hide();

});
Vitalii Petrychuk
  • 14,035
  • 8
  • 51
  • 55
0

no need of jquery... tou can just use the offsetWidth property of the element in the DOM

Yaron U.
  • 7,681
  • 3
  • 31
  • 45