Skip to content

Instantly share code, notes, and snippets.

@tilgovi
Last active August 29, 2015 14:27
Show Gist options
  • Save tilgovi/aba591cf857efbb847c0 to your computer and use it in GitHub Desktop.
Save tilgovi/aba591cf857efbb847c0 to your computer and use it in GitHub Desktop.
Reloading Hypothesis annotations on hash change
// Function to check whether an anchor is currently attached to the document.
function isAttached(anchor) {
// If there are no highlights it is not attached at all.
if (anchor.highlights == null) {
return false;
}
// Check if any of highlights have since been removed from the document.
for (var i = 0 ; i < anchor.highlights.length ; i++) {
if (!document.contains(anchor.highlights[i])) {
return false;
}
}
// Otherwise, this anchor appears to be fully attached.
return true;
}
// Function to anchor all detached annotations.
function reanchorAnnotations() {
var annotator = window.annotator;
var anchors = annotator.anchors.slice();
for (var i = 0 ; i < anchors.length ; i++) {
var anchor = anchors[i];
var annotation = anchor.annotation;
if (isAttached(anchor)) {
annotator.detach(annotation); // Clean up any remaining highlights.
annotator.anchor(annotation); // Then anchor and highlight anew.
}
}
}
window.addEventListener("hashchange", reanchorAnnotations, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment