Nefcairon

Nefcairon

Hello,

I am new to TailwindCSS and try to add a dark mode to a freshly generated phoenix app.

From Dark mode - Core concepts - Tailwind CSS I learned

  • to add darkMode: 'class' to my tailwind.config.js,
  • to add class="dark" to the html-tag, and
  • to put dark: in front of any color, like so dark:bg-black

That works so far, but the user is not able to switch between dark and normal mode yet. Is there a way to remove/add class="dark" from/to the html-tag on server side in pure elixir with Lieview or has this to be done via JS?

Showing Posts 1 to 8

shahryarjb

shahryarjb

For now, I have added "dark" to the <html> tag by LiveView JS hook

LostKobrakai

LostKobrakai

That’s what I’ve been using on my website:

// app.js
function darkExpected() {
  return localStorage.theme === 'dark' || (!('theme' in localStorage) &&
    window.matchMedia('(prefers-color-scheme: dark)').matches);
}

function initDarkMode() {
  // On page load or when changing themes, best to add inline in `head` to avoid FOUC
  if (darkExpected()) document.documentElement.classList.add('dark');
  else document.documentElement.classList.remove('dark');
}

window.addEventListener("toogle-darkmode", e => {
  if (darkExpected()) localStorage.theme = 'light';
  else localStorage.theme = 'dark';
  initDarkMode();
})

initDarkMode();

// trigger
// phx-click={JS.dispatch("toogle-darkmode")}
20
Post #2
BradS2S

BradS2S

You can use ETS to set up the initial value in the application

#start the ets lookup table
:ets.new(:my_ets, [:named_table, {:read_concurrency, true}])

#set theme_mode default
:ets.insert(:my_ets, {"theme_mode", :light})  
## true

add your toggle button

##toggle button
<button phx-click="toggle_mode">Toggle theme</button>

Monitor the click event

def handle_event("toggle_mode", _params, socket) do  
   toggle_theme_mode(socket)
   |> then( fn mode ->
   {:reply, %{mode: mode}, socket} end)

#toggle theme mode
defp toggle_theme_mode(socket) do
   case socket.assigns.theme_mode do
       :dark  -> assign(socket, :theme_mode, :light)
       :light  -> assign(socket, :theme_mode, :dark)
   end
end

include class={@theme_mode} in your template.

jean

jean

Just pointing up something that can help others: you should use color-scheme: dark; because it sets some CSS standards to dark color like inputs, scrollbars, and so on.

edit: some reference

azyzz228

azyzz228

use the power of AlpineJS?

Here is the tutorial on AlpineJS: https://youtu.be/r5iWCtfltso?t=2218.
here is how to add AlpineJS to Phoenix: How to combine Phoenix LiveView with Alpine.js · FullstackPhoenix (Steps 1 & 2)

I know writing JS is not something Elixir devs can be fan of, but I think implementation of dark/light mode is elegant with the help of AlpineJS. Also in this case, JS is not interacting with server and dealing solely with client-side feature, that makes it even more appropriate to use it in this case instead of making round-trips to the server LiveView way

azyzz228

azyzz228

so I went thru tailwind’s documentation, seems like you will need to add “dark” class to html tag and all dark:styles will be used

petrus-jvrensburg

petrus-jvrensburg

Based on the answers above, this is what I’m using:

// assets/tailwind.config.js
module.exports = {
  ...
  darkMode: 'class',
  ...
}
// assets/js/app.js:
function applyColorSchemePreference() {
    const darkExpected = window.matchMedia('(prefers-color-scheme: dark)').matches;
    if (darkExpected) {
        document.documentElement.classList.add('dark');
        document.documentElement.style.setProperty('color-scheme', 'dark');
    }
    else {
        document.documentElement.classList.remove('dark');
        document.documentElement.style.setProperty('color-scheme', 'light');
    }
}

// set listener to update color scheme preference on change
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', event => {
    const newColorScheme = event.matches ? "dark" : "light";
    console.log(newColorScheme);
    applyColorSchemePreference();
});

// check color scheme preference on page load
applyColorSchemePreference();

This doesn’t allow for manual toggling: it defers to the operating system. But it toggles automatically whenever the operating system switches between dark & light modes.

sergio

sergio

Thanks dude, this worked beautifully!

— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
kpanic
Hi everyone, I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding. I sta...
New
brecabral
Documentation While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
asweet-confluent
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
apz
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New

Other Trending Topics Top

GenericJam
Edit: 2026 May 15 - This post is archived. Mob is alive!! Main docs: mob v0.7.11 — Documentation A bit of explanation for the slightly c...
New
JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
mhanberg
Hi everyone! The first release candidate for the Expert language server project is now available! We’ve published a press release detai...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews