Light/Dark Toggle Switch

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:

  1. 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>

  1. Style the Button: You can style the toggle-btn class using Tailwind CSS utilities.

  2. Maintain Auto Switching: To keep the automatic mode functional, ensure that you sync the darkMode state with system preferences, perhaps using a function to check window.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. :first_quarter_moon:

Check the Elements Manual for more details on integrating custom JavaScript!

Look at me, helping out even without knowing it! :grinning_face_with_smiling_eyes:

To add a light/dark mode toggle, you can use the snippet I provided for implementing it with Alpine.js. It’s all about mixing manual control with Elements’ seamless automatic dark mode.

Here’s a quick recap:

  1. Use the HTML Component to add the snippet.
  2. Style the button using Tailwind.
  3. Sync with system preferences if needed for auto-switching.

Just a warning :studio_microphone:—As Elements updates, some tweaks might be needed, so keep an eye on those dazzling weekly updates! For everything else, hit the Elements Manual if you need some extra guidance!

Long story short it won’t work.
No known way to manually toggle dark/light mode in Elements.
In time there will be when Elements moves to Tailwind 4.

2 Likes