1

I am looking for a way to separately process the lines in a <div> that are wrapped due to a narrow width. That is, if my text is "Lorem ipsum dolor sit amet lorem \n ipsum dolor sit amet" and it is seen as below:

Lorem ipsum dolor
sit amet lorem
ipsum dolor sit
amet

Then I should be able to encapsulate each 'line' in a, say, <span> tag, such as:

<span id="line0">Lorem ipsum dolor<span>
<span id="line1">sit amet lorem</span>
... etc.

Edit: We can assume that the width and height of the div is fixed and known.

I couldn't find a proposed solution, if any exists; although there is a good suggestion for counting the lines for a fixed line-height: How to check for # of lines using jQuery

Community
  • 1
  • 1
kubuzetto
  • 1,046
  • 1
  • 12
  • 31

1 Answers1

1

Starting with this:

<div class="narrow">Lorem ipsum dolor sit amet lorem ipsum dolor sit amet</div>

css:

.narrow {
   width:60px;   
}

Insert some placeholders where there are spaces:

$('.narrow').html($('.narrow').html().replace(/ /g,"<span class='count'> </span>")) 

Determine the y-position of each placeholder:

$('.narrow .count') .each(function() {
     var myPos = $(this).position()
     alert(myPos.top)   
}) 

From there you should be able to figure out where the start/end points of each line based on its y-position.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176
  • Thank you for your answer, that seems doable and elegant. I also just found a similar question at http://stackoverflow.com/questions/3738490/finding-line-wraps I will try your and Inaimathi's suggestions. Thanks again. – kubuzetto Jan 31 '12 at 17:13