Reputation: 175
I have a div that expands and collapse on a button click that works just fine. I am now trying to see if it is possible to add a cookie to the JS that the div remembers the last state on a page reload.
The script I am using is:
The html:
<div id="myDIV" class="modal-body vcenter noti_open">
and the JS:
<script>
$("button").click(function(){
$(this).find("i").toggleClass("fa-chevron-up");
});
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("noti_close");
}
</script>
How to add a cookie to the browser to remember the change in state of #myDIV?
Upvotes: 0
Views: 347
Reputation: 11
Better to use localStorage instead of cookies. If something blocking you from using local storage, the following shlould work.
$("button").click(function(){
$(this).find("i").toggleClass("fa-chevron-up");
setCookie('toggle-satus', !toBoolean(getCookie('toggle-satus')), 7);
});
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("noti_close");
}
function setCookie(cname, cvalue, exdays) {
var now = new Date();
now.setTime(now.getTime() + (exdays*24*60*60*1000));
var expires = "expires="+ now.toUTCString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
function getCookie(cname) {
var name = cname + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for(var i = 0; i <ca.length; i++) {
var 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 toBoolean(str) {
return (str === "true");
}
$(this).load(function(){
var toggleStatus = toBoolean(getCookie('toggle-satus'));
if(toggleStatus){
var element = document.getElementById("myDIV");
element.addClass("noti_close");
}
})
Upvotes: 1
Reputation: 473
Use localstorage
:
$("button").click(function(){
$(this).find("i").toggleClass("fa-chevron-up");
localStorage.setItem('toggle-satus', ! (localStorage.getItem('toggle-satus') == "true") );
});
function myFunction() {
var element = document.getElementById("myDIV");
element.classList.toggle("noti_close");
}
$(this).load(function(){
var toggleStatus = (localStorage.getItem('toggle-satus') == "true");
if(toggleStatus){
var element = document.getElementById("myDIV");
element.addClass("noti_close");
}
})
Upvotes: 0