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" class="light">
<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" class="sh">dark black</div>
<div id="hs" class="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. :)
You can use local storage. Its very simple and better than 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 add an if statement on your function to check if class available set local storage item is set to black or not
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 );