rosamaria
rosamaria

Reputation: 13

Save dark mode in php cookies

I worked on a simple little code for black mode

I would just like to store the theme for the user in cookies for x time

My Dark Theme in css :

body {
  padding: 0px;
  color: black;
  font-size: 25px;
  background-color: white;
}

.dark-mode .mainSection {
  background-color: black;
  color: white;
  padding: 600px;
  padding-top: 470px;
}

Html

  <div id="dark-mode">
    <li><font size="2">
      <a class="nav-link" onclick="myFunction()">Dark Mode</font
    </li>
  </div>

Javascript :

  function myFunction() {
    var element = document.body;
    element.classList.toggle("dark-mode");

  } 

Thank you

Upvotes: 1

Views: 1964

Answers (1)

Utkarsh Dixit
Utkarsh Dixit

Reputation: 4275

Simply set the cookie using javascript, and the next time the client makes the request to server, the cookies will be send along with it. The below code should work

 function createCookie(name, value, timeInSeconds) {
       var date = new Date();
       date.setTime(date.getTime()+(timeInSeconds*1000));
       var expires = "; expires="+date.toGMTString();
    
       document.cookie = name+"="+value+expires+"; path=/";
 }

 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 "";
}

function myFunction() {
      var element = document.body;
      const isDarkModeOn = element.classList.toggle("dark-mode");
      createCookie("isDarkModeOn", isDarkMode.toString(), 60 * 60 * 24); // 1 day expiry date
}

window.onload = function () {
  const isDarkModeOn = getCookie("isDarkModeOn");
  if(isDarkModeOn === "true") document.body.classList.add("dark-mode");
}

After that simply check the cookie in PHP,

<?php
 $isDarkModeOn = $_COOKIE["isDarkModeOn"] === "true";
 if($isDarkModeOn) {
   echo "Dark Mode is on";
 }
?>

Upvotes: 1

Related Questions