Skip to content

Commit ba8652e

Browse files
committed
Restart animation on reconnection
1 parent f7043e5 commit ba8652e

File tree

1 file changed

+16
-13
lines changed

1 file changed

+16
-13
lines changed

sparkly-text.js

Lines changed: 16 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ let sparkleTemplate;
44
// https://caniuse.com/mdn-api_cssstylesheet_replacesync
55
const supportsConstructibleStylesheets = ("replaceSync" in CSSStyleSheet.prototype);
66

7+
const motionOK = window.matchMedia('(prefers-reduced-motion: no-preference)');
8+
79
class SparklyText extends HTMLElement {
810
#numberOfSparkles = 3;
911
#sparkleSvg = `<svg width="1200" height="1200" viewBox="0 0 1200 1200" aria-hidden="true">
@@ -77,19 +79,21 @@ class SparklyText extends HTMLElement {
7779
}
7880

7981
connectedCallback() {
80-
if (this.shadowRoot) {
81-
return;
82-
}
82+
const needsSparkles = motionOK.matches || !this.shadowRoot;
8383

84-
this.#numberOfSparkles = parseInt(
85-
this.getAttribute("number-of-sparkles") || `${this.#numberOfSparkles}`,
86-
10
87-
);
84+
if (!this.shadowRoot) {
85+
this.attachShadow({ mode: "open" });
86+
this.generateCss();
87+
this.shadowRoot.append(document.createElement("slot"));
88+
}
8889

89-
this.attachShadow({ mode: "open" });
90-
this.shadowRoot.append(document.createElement("slot"));
91-
this.generateCss();
92-
this.addSparkles();
90+
if (needsSparkles) {
91+
this.#numberOfSparkles = parseInt(
92+
this.getAttribute("number-of-sparkles") || `${this.#numberOfSparkles}`,
93+
10
94+
);
95+
this.addSparkles();
96+
}
9397
}
9498

9599
addSparkles() {
@@ -121,8 +125,7 @@ class SparklyText extends HTMLElement {
121125
});
122126

123127
setTimeout(() => {
124-
const {matches:motionOK} = window.matchMedia('(prefers-reduced-motion: no-preference)');
125-
if (motionOK && this.isConnected) this.addSparkle();
128+
if (motionOK.matches && this.isConnected) this.addSparkle();
126129
}, 2000 + Math.random() * 1000);
127130
}
128131
}

0 commit comments

Comments
 (0)