Home > Enterprise >  how to save toogle class with cookies? or help me with something similar/alternative to this one
how to save toogle class with cookies? or help me with something similar/alternative to this one

Time:01-30

function myFunction() {
{
   var element = document.getElementById("body");
   element.classList.toggle("bdark");
}
{
   var element = document.getElementById("theader");
   element.classList.toggle("hdark");
}
{
   var element = document.getElementById("sh");
   element.classList.toggle("shh");
}
{
  var x = document.getElementById("hs");
  if (x.style.display === "block") {
    x.style.display = "none";
  } else {
    x.style.display = "block";
  }
}
}
.bdark {
  background-color: #333;
  color: white;
}

.hdark {
  background-color: black;
  color: white;
}

.shh {
  display: none;
}

.hs {
  display: none;
}
<body id="body" >

<p id="theader">Click the "Try it" button to toggle between adding and removing the class names</p>

<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is a DIV element.
</div>

<div>
 <div id="sh" >dark black</div>
 <div id="hs" >light white</div>
</div>

i want it's class to be saved so when i refresh or reopen the page it would be same class as it was when i left. or some alternative code that works same. Thanks for Reading This. :)

CodePudding user response:

you can use localstorage. its very simple and better of cookies.

for example to set element bg color (on load):

if(localStorage.getItem("color") == "black") { element.classList.add("dark"); }

and on your function add :

localStorage.setItem("color",black or white )

note: you should be add an if statement on your func to if class available set locla storage item to black or not

CodePudding user response:

add this to end of jquery file (Mrbg => mr babak golbaharan :) )

$.extend({
  MrbgSetCookie:function(name,value,days){
    var expires = '';
    if (days) {
      var date = new Date();
      date.setTime(date.getTime()   (days*24*60*60*1000));
      expires = "; expires="   date.toUTCString();
    }
    document.cookie = name   "="   (value || "")    expires   "; path=/";
  },
  MrbgGetCookie:function(name){
    var nameEQ = name   "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i  ) {
      var c = ca[i];
      while (c.charAt(0)==' ') 
        c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) 
        return c.substring(nameEQ.length,c.length);
    }
    return null;
  },
  MrbgRemoveCookie:function(name){   
    document.cookie = name '=; Max-Age=-99999999;';  
  },
});

now you can use this for set, get and remove cookies such as this

$.MrbgSetCookie( 'cookieName', 'cookieValue' , 'period in day' );

in this case:

element = document.getElementById("body");
element.classList.toggle("bdark");   
    
( element.classList.contains('bdark') )?
  $.MrbgSetCookie( yourElementID, 'bdark' , 365 ):
  $.MrbgRemoveCookie(yourElementID );
  •  Tags:  
  • Related