Skip to content

Instantly share code, notes, and snippets.

@NickGard
Created August 2, 2024 17:47
Show Gist options
  • Save NickGard/b692ccf33312bf7bf0a6f22b5fd46228 to your computer and use it in GitHub Desktop.
Save NickGard/b692ccf33312bf7bf0a6f22b5fd46228 to your computer and use it in GitHub Desktop.
Click Redirector Component
(function () {
const clickRedirectorEventListenerSetKey = Symbol();
if (!window[clickRedirectorEventListenerSetKey]) {
window[clickRedirectorEventListenerSetKey] = true;
window.addEventListener(
"click",
(event) => {
const clickRedirector = event.target.closest("click-redirector");
const redirectedTarget = document.getElementById(
clickRedirector?.htmlFor
);
if (
clickRedirector /* click occurred inside click-redirector */ &&
redirectedTarget !==
event.target /* click is NOT on the redirected target */ &&
!event.defaultPrevented /* no previous listener canceled the event */
) {
event.preventDefault();
event.stopImmediatePropagation();
redirectedTarget.click();
}
},
{ capture: true }
);
}
})();
class ClickRedirector extends HTMLElement {
static observedAttributes = ["for"];
#htmlFor = "";
get htmlFor() {
return this.#htmlFor;
}
set htmlFor(val) {
this.#htmlFor = String(val);
}
attributeChangedCallback(name, oldValue, newValue) {
if (name === "for" && [this.#htmlFor, null].includes(oldValue)) {
// don't set if reflection is broken
this.#htmlFor = newValue;
}
}
}
customElements.define("click-redirector", ClickRedirector);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment