diff --git a/src/posts/article2.md b/src/posts/article2.md index c8e4dc1..a97fe6a 100644 --- a/src/posts/article2.md +++ b/src/posts/article2.md @@ -7,6 +7,71 @@ tags: ['Tips And Tricks', 'Demo'] For decades, South Florida schoolchildren and adults fascinated by far-off galaxies, earthly ecosystems, the properties of light and sound and other wonders of science had only a quaint, antiquated museum here in which to explore their interests. "Now, with the long-delayed opening of a vast new science museum downtown set for Monday, visitors will be able to stand underneath a suspended, 500,000-gallon aquarium tank and gaze at hammerhead and tiger sharks, mahi mahi, devil rays and other creatures through a 60,000-pound oculus, a lens that will give the impression of seeing the fish from the bottom of a huge cocktail glass." +```javascript +const storageKey = 'theme-preference' + +const onClick = () => { + // flip current value + theme.value = theme.value === 'light' + ? 'dark' + : 'light'; + + document + .querySelector('.theme-toggle') + .classList.toggle('theme-toggle--toggled'); + + setPreference() +} + +const getColorPreference = () => { + if (localStorage.getItem(storageKey)) + return localStorage.getItem(storageKey) + else + return window.matchMedia('(prefers-color-scheme: dark)').matches + ? 'dark' + : 'light' +} + +const setPreference = () => { + localStorage.setItem(storageKey, theme.value) + reflectPreference() +} + +const reflectPreference = () => { + document.firstElementChild + .setAttribute('data-theme', theme.value) + + document + .querySelector('#theme-toggle') + ?.setAttribute('aria-label', theme.value) +} + +const theme = { + value: getColorPreference(), +} + +// set early so no page flashes / CSS is made aware +reflectPreference() + +window.onload = () => { + // set on load so screen readers can see latest value on the button + reflectPreference() + + // now this script can find and listen for clicks on the control + document + .querySelector('.theme-toggle') + .addEventListener('click', onClick) +} + +// sync with system changes +window + .matchMedia('(prefers-color-scheme: dark)') + .addEventListener('change', ({matches:isDark}) => { + theme.value = isDark ? 'dark' : 'light' + setPreference() + }) +``` +
Placeholder