How to create light and dark mode
Posted: Mon Mar 27, 2023 9:08 pm
				
				please how do I create a light and dark more options in my site
			Code: Select all
<!DOCTYPE html>
<html>
<head>
	<title>Dark/Light Mode Toggle</title>
	<style>
		body {
			background-color: white;
			color: black;
		}
		.dark-mode {
			background-color: black;
			color: white;
		}
	</style>
</head>
<body>
	<h1>Dark/Light Mode Toggle</h1>
	<p>Click the button to toggle between dark and light mode:</p>
	<button onclick="toggleDarkMode()">Toggle dark mode</button>
	<script>
		function toggleDarkMode() {
			var element = document.body;
			element.classList.toggle("dark-mode");
		}
	</script>
</body>
</html>charmingdc wrote: ↑Mon Mar 27, 2023 9:08 pm please how do I create a light and dark more options in my site
Code: Select all
<select id="select_theme" onchange="select_theme()"><option value="style.css">light</option><option value="style.dark_mode.css">dark</option></select>Code: Select all
function select_theme() {
      var theme = document.getElementById("select_theme").value; // Get theme
      const d = new Date(); 
      d.setTime(d.getTime() + (30*24*60*60*1000));
      let expires = "expires="+ d.toUTCString();
      document.cookie = "theme=" + theme + ";" + expires + ";path=/"; // set cookie for user select theme
      window.location='/'; // redirect home if user select theme
    }Code: Select all
#%IFNOT(%COOKIE(theme)%)@THEN(<link rel="stylesheet" href="style.css" type="text/css" />)@ELSE(<link rel="stylesheet" href="%COOKIE(name)%.css" type="text/css" />)%#
Code: Select all
    /* Function get cookie by w3schools.com */
    function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for(let i = 0; i <ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return "";
}
// check user theme and use if darkmode screen
if (!getCookie('theme') && window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
     document.cookie = "theme=style.dark_mode.css;2592000000;path=/"; // set cookie theme darkmod
     window.location='/'; // redirect home
     console.log( "Auto change theme dark!" ); // press F12 button for view console.log
    }
    