Created
November 30, 2023 23:49
-
-
Save knowler/fd96f236ae82d8c7d83e18e726a3061a to your computer and use it in GitHub Desktop.
A web component for restarting all the animations on the page.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class RestartAnimationsElement extends HTMLElement { | |
#controller; | |
get #buttonElement() { return this.shadowRoot.querySelector(':host > button'); } | |
connectedCallback() { | |
if (!this.shadowRoot) { | |
this.attachShadow({mode: 'open'}); | |
this.shadowRoot.innerHTML = `<button type="button" part="button"><slot>Restart Animations</slot></button>`; | |
this.#controller = new AbortController(); | |
} | |
this.#buttonElement?.addEventListener( | |
'click', | |
this.#restartAnimations.bind(this), | |
{ signal: this.#controller.signal }, | |
); | |
} | |
disconnectedCallback() { | |
this.#controller.abort('element disconnected'); | |
} | |
#restartAnimations() { | |
for (const animation of this.ownerDocument.getAnimations()) { | |
animation.cancel(); | |
animation.play(); | |
} | |
} | |
static define() { | |
if (!window.customElements.get('restart-animations')) { | |
window.RestartAnimationsElement = RestartAnimationsElement; | |
window.customElements.define('restart-animations', RestartAnimationsElement); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment