Skip to content

Instantly share code, notes, and snippets.

@Elshaden
Last active February 7, 2021 01:18
Show Gist options
  • Save Elshaden/843cc70f23b369b2c11407a6f73fb24c to your computer and use it in GitHub Desktop.
Save Elshaden/843cc70f23b369b2c11407a6f73fb24c to your computer and use it in GitHub Desktop.
Toggle Dark Mode with Tailwind css. and Livewire
<script>
// This script should be placed in the main layout file ( layouts.app )
// You need to create Livewire component in this case called Theme,
//
// you only need to set the listener to 'ModeView' see gist of this component
// Initial load of the page
window.addEventListener("load", function(){
var mode = 'light';
//Check if User Has Set Pref from Application
if (('theme' in localStorage) ) {
switchMode( localStorage.theme)
}else{
// User Has No Preference, So Get the Browser Mode ( set in Computer settings )
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
mode = 'dark';
} else{
mode = 'light';
}
localStorage.theme =mode ;
// Inform Livewire of the Mode so that It toggles the DarkMode set in Tailwind.config.js
Livewire.emitTo('theme','ModeView',localStorage.theme)
switchMode(mode)
}
});
// In case the use changed the moe from Browser Pref, Then Override the Application Settings
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
const newColorScheme = e.matches ? document.documentElement.classList.add('dark') : document.documentElement.classList.remove('dark');
localStorage.theme = newColorScheme;
Livewire.emitTo('theme','ModeView', e.matches? 'dark': 'light')
});
function switchMode(mode){
if( localStorage.theme === 'dark'){
document.documentElement.classList.add('dark')
}else{
document.documentElement.classList.remove('dark')
}
Livewire.emitTo('theme','ModeView',mode)
}
// this emitted from Livewire to change the Class DarkMoe on and Off.
window.addEventListener('view-mode', event => {
localStorage.theme =event.detail.newMode ;
switchMode(event.detail.newMode);
});
</script>
// Theme Component
namespace App\Http\Livewire;
use Livewire\Component;
class Theme extends Component
{
protected $listeners =['ModeView'];
public $mode;
public function ModeView($Color){
$this->mode = $Color;
}
public function SwitchMode($SwitcMode){
// you need to add the switch somewhere in your code to be able to toggle the mode
$this->mode = $SwitcMode;
$newMode = $SwitcMode =='dark'?'light':'dark';
$this->dispatchBrowserEvent('view-mode', ['newMode' => $newMode]);
}
// No Render Method is needed
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment