Let\'s say we have a long text like Romeo & Juliet and we want to present this in a simple ereader (no animations, only pages and custom font-size). What approaches exis
I have got a solution with quite simple, changable css markup and 3 pretty short js functions.
First I have created two div-elements, from which one is hidden but contains the whole text and the other is displayed but empty yet. The HTML would look like this:
some text here
the CSS for these two is:
#originalText{
display: none; // hides the container
}
#paginatedText{
width: 300px;
height: 400px;
background: #aaa;
}
also I made the css ready for a class names page which looks like this:
.page{
padding: 0;
width: 298;
height: 398px; // important to define this one
border: 1px solid #888;
}
the really important part is to define the height because otherwise the pages will just get streched when we fill in the words later on.
Now comes the important part. The JavaScript functions. The comments should speak for themself.
function paginateText() {
var text = document.getElementById("originalText").innerHTML; // gets the text, which should be displayed later on
var textArray = text.split(" "); // makes the text to an array of words
createPage(); // creates the first page
for (var i = 0; i < textArray.length; i++) { // loops through all the words
var success = appendToLastPage(textArray[i]); // tries to fill the word in the last page
if (!success) { // checks if word could not be filled in last page
createPage(); // create new empty page
appendToLastPage(textArray[i]); // fill the word in the new last element
}
}
}
function createPage() {
var page = document.createElement("div"); // creates new html element
page.setAttribute("class", "page"); // appends the class "page" to the element
document.getElementById("paginatedText").appendChild(page); // appends the element to the container for all the pages
}
function appendToLastPage(word) {
var page = document.getElementsByClassName("page")[document.getElementsByClassName("page").length - 1]; // gets the last page
var pageText = page.innerHTML; // gets the text from the last page
page.innerHTML += word + " "; // saves the text of the last page
if (page.offsetHeight < page.scrollHeight) { // checks if the page overflows (more words than space)
page.innerHTML = pageText; //resets the page-text
return false; // returns false because page is full
} else {
return true; // returns true because word was successfully filled in the page
}
}
At the end I just called the paginateText
function with
paginateText();
This whole skript works for every text and for every style of the pages.
So you can change the font and the font size and even the size of the pages.
I also have a jsfiddle with everything in there.
If I have forgotten anything or you have a question feel free to comment and make suggestions or ask questions.