Dynamic dark mode support (à la "@media prefers-color-scheme: dark")?

In searching for dark mode support in Algolia’s search bar/results, I’ve found:

Is it possible to dynamically set the Algolia search bar/results based on the user’s settings similar to CSS’s “@media (prefers-color-scheme: dark)”?

Hi, we indeed don’t support dynamic theme.
Using “@media (prefers-color-scheme: dark)” would indeed be a great addition, it could even be done in the Autocomplete’s default theme.
For now you will have to customize the CSS yourself (you can clone the repo and rebuild our default UI). But we’ve noted the idea!

1 Like

Thanks for letting me know, @sylvain.bellone.

Is there a sample by any chance of the bare-minimum CSS required to render the search box and results properly?

I tried starting by eliminating the CSS altogether, but the result displayed a search button which had to be clicked in order to reveal the search box (though the results did appear correctly after that). On a related note, is it possible just to use a standard text input form and display results on a new page instead?

If there is no existing bare bones CSS example, I’ll get to work sorting one out - thanks again!

So our frontend imports the Autocomplete’s autocomplete-theme-classic. You can find a link to the complete CSS file on that page, and all the variables that are exposed.

Yeah I know that it looks weird without CSS :slight_smile: . And no you can’t use a standard text input with Autocomplete, for that you will need to implement something custom and probably create a separate results page with InstantSearch.

1 Like

Got it - thank you again!

1 Like

I cobbled together an automatic light/dark mode switcher for the search bar and results by adding an if…else statement to algoliasearchNetlify in the default HTML snippet:

if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
	algoliasearchNetlify({
		appId: 'XXXXXXXXXX',
		apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
		siteId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
		branch: 'master',
		selector: 'div#search',
		theme: {
			mark: '#fff',
			background: '#23263b',
			selected: '#111432',
			text: '#d6d6e7',
			colorSourceIcon: '#d6d6e7'
		}
	});
} else {
	algoliasearchNetlify({
		appId: 'XXXXXXXXXX',
		apiKey: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
		siteId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
		branch: 'master',
		selector: 'div#search'
	})
}

Sources: Mark Szabo’s answer to How do I detect dark mode using JavaScript? and Algolia’s front-end configuration documentation for the Netlify plugin. (I’m certain a JS wizard would come up with something far more elegant, though that’s no reflection on the aforementioned sources, but rather my nonexistent JS knowledge.)

2 Likes

Excellent workaround, thanks for sharing :slight_smile:

1 Like