Skip to content

Instantly share code, notes, and snippets.

@knowler
Created November 30, 2023 23:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knowler/fd96f236ae82d8c7d83e18e726a3061a to your computer and use it in GitHub Desktop.
Save knowler/fd96f236ae82d8c7d83e18e726a3061a to your computer and use it in GitHub Desktop.
A web component for restarting all the animations on the page.
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