Skip to content

Niyander Tech

Learn with fun

Menu
  • Home
  • Categories
    • Android
    • Alpine.js Components
    • Genshin Impact News
    • Jobs and Internship
    • Coursera Hub
  • Our Policies
    • Privacy Policy
    • Terms and Conditions
    • Contact Us
  • Coursera Search Engine
  • AI Tools
    • AI Background Remover
    • AI Video Downloader
    • 98+ Beautiful CSS Box-Shadow
    • G-Drive Download Link Generator
Menu
Building a Dark Mode Toggle with Alpine.js and Tailwind CSS

Building a Dark Mode Toggle with Alpine.js and Tailwind CSS

Posted on April 9, 2025April 9, 2025 by Niyander

In this article, I will show you how to create a Dark Mode Toggle with Alpine.js. It’s a simple and effective way to add a modern touch to your website. With just a few lines of code, you can switch between light and dark themes effortlessly.

Alpine.js makes the whole process easy, even if you’re new to JavaScript. By the end, you’ll have a smooth toggle feature that’s both functional and fun to build.”

Dark mode is not just trendy — it’s easier on the eyes and can make your site feel modern. In this quick tutorial, you’ll learn how to build a dark mode toggle using Alpine.js and Tailwind CSS, with no frameworks or complex setup needed.

Table of Contents

  • What You’ll Need
  • Dark Mode Toggle Demo #1
  • Dark Mode Toggle Demo #2
  • Let’s Building a Dark Mode Toggle with Alpine.js
  • Step 1: Set Up Tailwind with Dark Mode
  • Step 2: Add Alpine.js to Your HTML
  • Step 3: Create the Toggle Button
  • How It Works
  • Download Code
  • Conclusion

What You’ll Need

  • Basic HTML knowledge
  • Tailwind CSS (with dark mode enabled)
  • Alpine.js (v3+)

Dark Mode Toggle Demo #1


Dark Mode Toggle Demo #2

Let’s Building a Dark Mode Toggle with Alpine.js

Now, let’s dive into the implementation. I’ll guide you through each step in a simple and easy-to-follow way, so you can quickly set up your Dark Mode Toggle using Alpine.js!

Step 1: Set Up Tailwind with Dark Mode

First, make sure Tailwind is set up with class-based dark mode. In your tailwind.config.js:

module.exports = {
  darkMode: 'class', // Enable class-based dark mode
  content: ['./index.html'],
  theme: {
    extend: {},
  },
  plugins: [],
}

This lets you control dark mode manually by adding a dark class to the <html> or <body> tag.

Step 2: Add Alpine.js to Your HTML

Include Alpine.js via CDN before the closing </body> tag:

<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>

Step 3: Create the Toggle Button

Now let’s build the toggle itself:

<!DOCTYPE html>
<html lang="en" x-data="darkModeComponent()" x-init="init()">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>alpinejs Dark Mode Toggle</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      darkMode: 'class', 
    }
  </script>
  <script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
</head>
<body class="min-h-screen bg-white dark:bg-gray-900 text-black dark:text-white flex items-center justify-center transition-all">
  <div class="text-center">
    <h1 class="text-3xl mb-6">🌗 Dark Mode Toggle</h1>
	<!-- Toggle button -->   
   <button
      @click="toggleDarkMode"
      class="px-4 py-2 rounded-lg bg-gray-200 dark:bg-gray-800 text-black dark:text-white shadow transition-all">
      Toggle Dark Mode
    </button>
  </div>

<!-- Main alpinejs code for darkmode -->
  <script>
    function darkModeComponent() {
      return {
        darkMode: false,
        init() {
          this.darkMode = localStorage.getItem('darkMode') === 'true';
          this.updateHtmlClass();
        },
        toggleDarkMode() {
          this.darkMode = !this.darkMode;
          localStorage.setItem('darkMode', this.darkMode);
          this.updateHtmlClass();
        },
        updateHtmlClass() {
          document.documentElement.classList.toggle('dark', this.darkMode);
        }
      }
    }
  </script>
</body>
</html>

How It Works

  • Alpine’s x-data sets up a darkMode variable.
  • On load (x-init), we check localStorage to remember the user’s last choice.
  • x-effect watches darkMode and updates both the DOM and localStorage.
  • The document.documentElement.classList.toggle('dark') adds or removes the dark class on <html>.

You can also read these article: How to Create a Countdown Timer with Alpine.js

Download Code

Download Basic
Download Fancy

Conclusion

Alpine.js is great if you want a small, easy tool for web pages or quick little projects. It’s simple to use and doesn’t slow anything down.

just a few lines of Alpine.js and Tailwind CSS, you’ve built a fully functional dark mode toggle that looks great and remembers user preferences. This approach keeps things lightweight, JavaScript-free (besides Alpine), and totally customizable.

Dark mode is a small feature that makes a big impact on user experience — and now you’ve got the skills to add it to any project quickly.

Keep experimenting, and don’t be afraid to level it up with icons, transitions, or even system preference detection!

Happy coding!

Category: Alpine.js Components

Post navigation

← Intro to Networking and Cloud Computing Quiz Answers + Review
Cybersecurity Threat Vectors and Mitigation Quiz Answers + Review →

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Notice

Hey guys! Need a Google Drive Direct Download Link Generator? I made a simple tool that does just that. 🚀
Convert any shared Drive link into a direct download link instantly.
Try it out now: https://niyander.com/projects/tools/gdrive/
Let me know your thoughts!

Notice

Hi everyone! I've built a collection of 98+ CSS Box-Shadow Examples for developers and designers! 🎨
Click on any card to copy the shadow — super handy for your projects.
Explore them all here: https://niyander.com/projects/tools/box-shadow/
Hope you find it useful!

Notice

Hey folks! Excited to share my new tool — an All-in-One Social Media Downloader! 📥
Download videos, photos, and audio from TikTok, YouTube, Instagram, Facebook, and more.
Check it out here: https://niyander.com/projects/tools/sm/
Your feedback is welcome!

Notice

Hey friends! I just launched a free AI Background Remover called Panda AI! 🐼
Easily remove backgrounds from images with just one click.
Try it out now: https://niyander.com/projects/tools/bg/
Let me know what you think!

May 2025
M T W T F S S
 1234
567891011
12131415161718
19202122232425
262728293031  
« Apr    

About

Greetings, Hey i am Niyander, and I hail from India, we strive to impart knowledge and offer assistance to those in need.

  • Alpine.js Components
  • Android
  • Bootstrap
  • Coursera Hub
  • Genshin Impact News
  • Jobs and Internship
  • Uncategorized

Hot Topics

  • Microsoft Azure Data Scientist Associate (DP-100) Quiz Answers + Review
  • Prepare for DP-100: Data Science on Microsoft Azure Exam Answers + Review
  • Genshin Impact Version 5.6 redeem codes
  • More Software Engineering Jobs in Japan for Expats – April 2025 Edition
© 2025 Niyander Tech | Powered by Minimalist Blog WordPress Theme