Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding line-wraps

Supposing I have some random block of text in a single line. Like so

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

But for whatever reason (width settings on the containing element, use of text-zoom etc.), on the viewer's screen it displays as two or more lines.

Lorem ipsum dolor sit amet,

consectetur adipiscing elit.

or

Lorem ipsum dolor sit

amet, consectetur

adipiscing elit.

Is there any way to find out via javascript where those line-wraps happen?

$('p').text() and $('p').html() return Lorem ipsum dolor sit amet, consectetur adipiscing elit. regardless of how the text is displayed.

like image 475
Inaimathi Avatar asked Sep 17 '10 19:09

Inaimathi


People also ask

What is line wrap in microsoft word?

In text display, line wrap is continuing on a new line when a line is full, so that each line fits into the viewable window, allowing text to be read from top to bottom without any horizontal scrolling.

What should you do to avoid line wrap?

If you want to prevent the text from wrapping, you can apply white-space: nowrap; Notice in HTML code example at the top of this article, there are actually two line breaks, one before the line of text and one after, which allow the text to be on its own line (in the code).

Why word wrap?

Word wrap is a word processing feature that forces all text to be confined within defined margins. When a line of text is filled, the word processor automatically moves the text to the next line, so the user doesn't have to press the return key after every line.


1 Answers

Well, if you want something that's ridiculously simple and probably too useless for you (it'll need major modification if you have any sort of HTML inside the paragraph), then have a look at this:

var para = $('p');  para.each(function(){     var current = $(this);     var text = current.text();     var words = text.split(' ');      current.text(words[0]);     var height = current.height();      for(var i = 1; i < words.length; i++){         current.text(current.text() + ' ' + words[i]);          if(current.height() > height){             height = current.height();             // (i-1) is the index of the word before the text wraps             console.log(words[i-1]);         }     } }); 

It's so ridiculously simple it might just work. What this does is to break up the text by spaces, then append the words back word by word, watching for any increase in the height of the element, which would indicate a line wrap.

Have a look at it here: http://www.jsfiddle.net/xRPYN/2/

like image 182
Yi Jiang Avatar answered Sep 17 '22 20:09

Yi Jiang