Skip to content

Instantly share code, notes, and snippets.

@mosidrum
Created March 27, 2025 05:55
Show Gist options
  • Save mosidrum/e6ac6e0075ab4882d407706314e3345d to your computer and use it in GitHub Desktop.
Save mosidrum/e6ac6e0075ab4882d407706314e3345d to your computer and use it in GitHub Desktop.
Highlighting text playground
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Lampstand Epub</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/epub.min.js"></script>
<style>
#viewer {
width: 600px;
height: 100vh;
margin: 0 auto;
}
.highlight-yellow {
background-color: yellow;
}
</style>
</head>
<body>
<div id="viewer"></div>
<script>
window.onload = () => {
const book = ePub("./one-million-followers.epub");
const rendition = book.renderTo("viewer", {
width: "600px",
height: "100vh",
manager: "continuous",
flow: "scrolled",
});
rendition.display();
const restoreHighlights = () => {
const savedHighlights = JSON.parse(
localStorage.getItem("epub-highlights") || "[]"
);
savedHighlights.forEach((highlight) => {
rendition.annotations.highlight(
highlight.cfiRange,
{},
(element) => {
if (element) {
element.className = "highlight-yellow";
}
}
);
});
};
book.ready.then(() => {
restoreHighlights();
});
rendition.on("selected", (cfiRange) => {
if (!cfiRange || typeof cfiRange !== "string") {
console.error("Invalid CFI range:", cfiRange);
return;
}
book.getRange(cfiRange).then((range) => {
if (!range) return;
const selectedText = range.toString();
console.log("Selected text:", selectedText);
rendition.annotations.remove(cfiRange, "highlight");
rendition.annotations.highlight(cfiRange, {}, (element) => {
if (element) {
element.className = "highlight-yellow";
}
});
const savedHighlights = JSON.parse(
localStorage.getItem("epub-highlights") || "[]"
);
const newHighlight = {
text: selectedText,
cfiRange: cfiRange,
};
savedHighlights.push(newHighlight);
localStorage.setItem(
"epub-highlights",
JSON.stringify(savedHighlights)
);
});
});
};
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment