Skip to content

Instantly share code, notes, and snippets.

@MariusBongarts
Last active March 19, 2024 14:02
Show Gist options
  • Save MariusBongarts/557b0d23ed993483c8b9eeb384f24120 to your computer and use it in GitHub Desktop.
Save MariusBongarts/557b0d23ed993483c8b9eeb384f24120 to your computer and use it in GitHub Desktop.
MediumHighlighter - Custom element
class MediumHighlighter extends HTMLElement {
get markerPosition() {
return JSON.parse(this.getAttribute("markerPosition") || "{}");
}
get styleElement() {
return this.shadowRoot.querySelector("style");
}
get highlightTemplate() {
return this.shadowRoot.getElementById("highlightTemplate");
}
static get observedAttributes() {
return ["markerPosition"];
}
constructor() {
super();
this.render();
}
render() {
this.attachShadow({ mode: "open" });
const style = document.createElement("style");
style.textContent = styled({});
this.shadowRoot.appendChild(style);
this.shadowRoot.innerHTML += template;
this.shadowRoot
.getElementById("mediumHighlighter")
.addEventListener("click", () => this.highlightSelection());
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === "markerPosition") {
this.styleElement.textContent = styled(this.markerPosition);
}
}
highlightSelection() {
var userSelection = window.getSelection();
for (let i = 0; i < userSelection.rangeCount; i++) {
this.highlightRange(userSelection.getRangeAt(i));
}
window.getSelection().empty();
}
highlightRange(range) {
const clone =
this.highlightTemplate.cloneNode(true).content.firstElementChild;
clone.appendChild(range.extractContents());
range.insertNode(clone);
}
}
window.customElements.define("medium-highlighter", MediumHighlighter);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment