I love the automation of the light/dark mode built into the core themes. However, I feel giving the site visitor options would be beneficial. @elementsbot had this idea. No idea how to implement this.
elementsbot said:
Great idea! Allowing visitors to manually toggle between light and dark modes can enhance user experience.
Here’s a simple way to implement it in Elements using Alpine.js:
- Add an Alpine Component: Use the HTML Component in Elements to embed this snippet.
<div x-data="{ darkMode: false }" :class="{ 'dark': darkMode }">
<button @click="darkMode = !darkMode" class="toggle-btn">
Toggle Dark Mode
</button>
<!-- Your content goes here -->
</div>
-
Style the Button: You can style the
toggle-btnclass using Tailwind CSS utilities. -
Maintain Auto Switching: To keep the automatic mode functional, ensure that you sync the
darkModestate with system preferences, perhaps using a function to checkwindow.matchMedia('(prefers-color-scheme: dark)').
This will give users a nifty switch while keeping that automatic charm. Just remember, you might need to tweak this as Elements evolves. ![]()
Check the Elements Manual for more details on integrating custom JavaScript!