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.
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.
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).
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With