Skip to content

Instantly share code, notes, and snippets.

@MariusBongarts
Last active July 30, 2021 21:45
Show Gist options
  • Save MariusBongarts/23334ca6fa64eb5603bae86c23ba767b to your computer and use it in GitHub Desktop.
Save MariusBongarts/23334ca6fa64eb5603bae86c23ba767b to your computer and use it in GitHub Desktop.
MediumHighlighter - content.js final
const getSelectedText = () => window.getSelection().toString();
document.addEventListener("click", () => {
if (getSelectedText().length > 0) {
setMarkerPosition(getMarkerPosition());
}
});
document.addEventListener("selectionchange", () => {
if (getSelectedText().length === 0) {
setMarkerPosition({ display: "none" });
}
});
function getMarkerPosition() {
const rangeBounds = window
.getSelection()
.getRangeAt(0)
.getBoundingClientRect();
return {
// Substract width of marker button -> 40px / 2 = 20
left: rangeBounds.left + rangeBounds.width / 2 - 20,
top: rangeBounds.top - 30,
display: "flex",
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment