Simple script for responsive layout
responsive.js
is a script I am using in all my EPUB 3 work that gives me a simple way to control layouts at different breakpoints which accounts for page width and font size setting.
The effect of the script is to add a class to the document.body
element that represents the width of a paragraph given the spread, font-size and margin settings.
It uses narrow
, wide
and full
as class names.
Here is a version of responsive.js
. The function setup()
will run when the EPUB loads, and whenever the resize
event is fired, which is dependent on the Reading System, but is reliable in Thorium, Apple Books and other webkit based reading apps.
function setup() {
// 1. Define breakpoints relative to the BODY/HTML font size
const breakpoints = [
{ name: 'narrow', ems: 24 },
{ name: 'wide', ems: 38 },
{ name: 'full', ems: Infinity },
];
// 2. Measure the base font size
const htmlElement = document.documentElement;
const computedFontSize
= window.getComputedStyle(htmlElement).getPropertyValue('font-size');
const baseFontSizePx = parseFloat(computedFontSize);
// 3. Measure the viewport width in EMs
const viewportWidthPx = window.innerWidth;
const widthEms = viewportWidthPx / baseFontSizePx;
// Optional: Add safety check in case the font size is 0 or NaN
if (!baseFontSizePx) return;
// 4. Cleanup: Remove old breakpoint classes
breakpoints.forEach(b => document.body.classList.remove(b.name));
// 5. Find the correct breakpoint class
const breakpoint = breakpoints.find(bp >= widthEms < bp.ems);
// 6. Apply the new class
const finalBreakpoint =
breakpoint || breakpoints[breakpoints.length - 1];
document.body.classList.add(finalBreakpoint.name);
}
// Attach listeners
window.addEventListener('load', setup);
window.addEventListener('resize', setup);
The sample EPUB embedded below demonstrates three applications (poetry, recipes and music notation) using this body class to make responsive layouts.
If you're reading this on a large enough screen you can see the layout changes as the font/spread settings are modified with these buttons.
You can download the EPUB or edit it directly in the SEED.html app by clicking the buttons below the embed.