Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting line-breaks in browser/css-forced line breaks

<p style="width:60px"> I am some random text. I am Some text.blabla</p>

The rendered HTML result of above might be,

I am some ra
ndom text. I
am Some text
.blabla

I would like to split the above paragraph into separate paragraphs row by row. So what the expected result is like,

<p style="width:60px">I am some ra</p>
<p style="width:60px">ndom text. I</p>
<p style="width:60px">am Some text</p>
<p style="width:60px">.blabla</p>

Is it possible to implement it in Javascript?

P.S. Why do I have to split it? Because I would like to get my own pagination system for a long HTML, where all the paragraphs and splited paragraphs within a height range would be put in to a same <div class="page"></div>. Finally, the whole HTML would be organized as

<div id="page1" class="page">
   <p> complete content </p>
   <p> upper part of XXX </p>
</div>

<div id="page2" class="page">
   <p> bottom part of XXX </p>
   <p>...</p><p>...</p>
</div>
like image 661
ppn029012 Avatar asked Oct 21 '22 04:10

ppn029012


1 Answers

Well, assume that your text is in a <p id='wholeText'> :

var element = document.getElementById("wholeText");

var wholeText = element.innerHTML;

var splitText = wholeText.split("\r\n");

var newHtml = null;

for(var i = 0; i < splitText.length; i++)
{
   newHtml += "<p class='each-line'>"+splitText[i]+'</p>';
}

Then you can use newHtml to write in a DOM element. For instance, if you like to add it to a the same <p> which you got text from, you do:

element.innerHTML = newHtml; // remember element refers to the <p> with the ID of wholeText

Also put all of the above codes into a function and call the function after the windows has been fully loaded.

window.addEventListener("load", function(){

// put the code here
}, false);

If your line does not contain break characters, then please refer to this plugin : http://jsfiddle.net/nathan/qkmse/

The above link is suggested in this SO's question:

detecting line-breaks with jQuery?

like image 126
Mostafa Talebi Avatar answered Oct 24 '22 12:10

Mostafa Talebi