theme.js (1609B)
1 (function(){ 2 3 // Select the button 4 const btnTheme = document.getElementById('theme'); 5 // Check for dark mode preference at the OS level 6 const prefersDarkScheme = window.matchMedia('(prefers-color-scheme: dark)'); 7 8 // Get the user's theme preference from local storage, if it's available 9 const currentTheme = localStorage.getItem('theme'); 10 // If the user's preference in localStorage is dark... 11 if (currentTheme == 'dark') { 12 // ...let's toggle the .dark-theme class on the body 13 document.body.classList.toggle('dark-theme'); 14 // Otherwise, if the user's preference in localStorage is light... 15 } else if (currentTheme == 'light') { 16 // ...let's toggle the .light-theme class on the body 17 document.body.classList.toggle('light-theme'); 18 } 19 20 // Listen for a click on the button 21 btnTheme.addEventListener('click', function() { 22 // If the user's OS setting is dark and matches our .dark-theme class... 23 if (prefersDarkScheme.matches) { 24 // ...then toggle the light mode class 25 document.body.classList.toggle('light-theme'); 26 // ...but use .dark-theme if the .light-theme class is already on the body, 27 var theme = document.body.classList.contains('light-theme') ? 'light' : 'dark'; 28 } else { 29 // Otherwise, let's do the same thing, but for .dark-theme 30 document.body.classList.toggle('dark-theme'); 31 var theme = document.body.classList.contains('dark-theme') ? 'dark' : 'light'; 32 } 33 // Finally, let's save the current preference to localStorage to keep using it 34 localStorage.setItem('theme', theme); 35 }); 36 37 })();