Skip to content
MuffinWithJam edited this page Feb 9, 2017 · 10 revisions

This page has some useful snippets of code to use with epub.js v0.2. Note that this page assumes that your book was loaded into an object named book.

Table of Contents

Generating and getting page numbers

To use pagination, first you have to generate the page numbers. This will return a promise which completes after the pagination is generated:

book.generatePagination().then(function () {
    console.log("The pagination has been generated");
});

To have pagination consistent across different window sizes, you can specify a fixed size in pixels for each page:

var width = 600;
var height = 600;

book.generatePagination(width, height).then(function () {
    console.log("The pagination has been generated");
});

To get the page number of a CFI:

book.pagination.pageFromCfi(cfiGoesHere);
/* This returns a page number as an Integer */

To get the current page:

book.pagination.pageFromCfi(book.getCurrentLocationCfi());
/* This returns a page number as an Integer */

Searching the current chapter

To search the current chapter of the book for some text, you can use the following code:

book.currentChapter.find("Some Text to look for");

/*
 *  This returns an array of objects like: 
 * [{
 *     "cfi": "epubcfi(/6/18[chap-1]!4/2/30/1:24,1:31)",
 *     "excerpt": "...here is some text to look for..."
 * }, {
 *     "cfi": "epubcfi(/6/18[chap-1]!4/2/66/1:22,1:29)",
 *     "excerpt": "...I have found some more text to look for in this book..."
 * }]
 * 
 * The array can be looped over with a for loop, and used for search results. 
 * This function is case insensitive.
 * Note that this only searches the current chapter.
 * 
 */

Loading a book from a file input

Demo

This only works with browsers which support ArrayBuffer.

Add this to your HTML:

<input type="file" accept="application/epub+zip" id="bookChooser">

And this to your JavaScript:

book = null;
document.getElementById('bookChooser').addEventListener('change', function(e) {
    var firstFile = e.target.files[0];
    if (window.FileReader) {
        var reader = new FileReader();
        reader.onload = function(e) {
            book = ePub({ bookPath: e.target.result });

            book.renderTo("area"); 
            /* Replace area with the id for your div to put the book in */
        }.bind(this);

        reader.readAsArrayBuffer(firstFile);
    } else {
        alert("Your browser does not support the required features. Please use a modern browser such as Google Chrome, or Mozilla Firefox");
    }
});

Adding a page transition animation

The following code will give you an animation between pages.

EPUBJS.Hooks.register('beforeChapterDisplay').pageAnimation = function (callback, renderer) {
    window.setTimeout(function () {
        var style = renderer.doc.createElement("style");
        style.innerHTML = "*{-webkit-transition: transform {t} ease;-moz-transition: tranform {t} ease;-o-transition: transform {t} ease;-ms-transition: transform {t} ease;transition: transform {t} ease;}";
        style.innerHTML = style.innerHTML.split("{t}").join("0.5s");
        renderer.doc.body.appendChild(style);
    }, 100)
    if (callback) {
        callback();
    }
};

Also, at the moment, to support desktop and laptop devices, epub.js needs to be patched by adding the following code somewhere before you start using epub.js, but after you load the library. The only difference this makes is that epub.js will use css transforms on desktop devices as well as mobile devices to move the pages.

EPUBJS.Render.Iframe.prototype.setLeft = function(leftPos){
    this.docEl.style[this.transform] = 'translate('+ (-leftPos) + 'px, 0)';
}

Adding swipe support on touchscreens

The following code will allow you to swipe the pages on touchscreens.

EPUBJS.Hooks.register('beforeChapterDisplay').swipeDetection = function (callback, renderer) {
    var script = renderer.doc.createElement('script');
    script.text = "!function(a,b,c){function f(a){d=a.touches[0].clientX,e=a.touches[0].clientY}function g(f){if(d&&e){var g=f.touches[0].clientX,h=f.touches[0].clientY,i=d-g,j=e-h;Math.abs(i)>Math.abs(j)&&(i>a?b():i<0-a&&c()),d=null,e=null}}var d=null,e=null;document.addEventListener('touchstart',f,!1),document.addEventListener('touchmove',g,!1)}";
    /* (threshold, leftswipe, rightswipe) */
    script.text += "(10,function(){parent.ePubViewer.Book.nextPage()},function(){parent.ePubViewer.Book.prevPage()});"
    renderer.doc.head.appendChild(script);
    if (callback) {
        callback();
    }
};

Allowing keyboard arrow keys to control the pages

The following code allows you to use your left and right arrow keys to control the pages.

EPUBJS.Hooks.register("beforeChapterDisplay").pageTurns = function (callback, renderer) {
    var lock = false;
    var arrowKeys = function (e) {
        e.preventDefault();
        if (lock) return;

        if (e.keyCode == 37) {
            ePubViewer.Book.prevPage();
            lock = true;
            setTimeout(function () {
                lock = false;
            }, 100);
            return false;
        }

        if (e.keyCode == 39) {
            ePubViewer.Book.nextPage();
            lock = true;
            setTimeout(function () {
                lock = false;
            }, 100);
            return false;
        }

    };
    renderer.doc.addEventListener('keydown', arrowKeys, false);
    if (callback) callback();
}