dai11y 28/02/2023

Your daily frequent11y newsletter, brought to you by @ChrisBAshton:

Progressively-enhanced dark mode

Darin Senneff writes an incredibly in depth article about his progressively enhanced dark mode toggler.

Darin opts for a HTML form with three radio buttons: ‘auto’, ‘light’ and ‘dark’. The ‘auto’ option looks at the user’s operating system level preferences, i.e. serving light mode by default, but with a prefers-color-scheme media query that overrides to dark mode if that is the user’s theme preference.

If the user makes an active choice by submitting the form, he saves their preference in a session cookie, which persists as the user navigates around the site. He also keeps the selected theme pre-checked in the form, so it’s clear to the user which option they have selected. The explicit choice is used to apply a data-theme="dark" attribute on the root <html> element, and leads to some unavoidable CSS duplication as we now need to style based on the data attribute or user device theme.

Darin doesn’t stop there, and uses JavaScript to replace the form with a button. Triggering the button opens a dialog/modal, where the user can configure all of their preferences in one place, as well as have a live preview – and submission – of their chosen theme without having to refresh the page. Darin walks us through listening for all the necessary keyboard events for things like exiting the modal.

The user’s choice is now persisted in localStorage with JavaScript, which is more persistent than a session cookie, and thus able to store the user’s preference between visits.


Prefer longer newsletters? You can subscribe to week11y, fortnight11y or even month11y updates! Every newsletter gets the same content; it is your choice to have short, regular emails or longer, less frequent ones. Curated with ♥ by developer @ChrisBAshton.

Loading...