-1

I want to make a sidebar on my website which works something like "When the first time a logged-in user comes on the page the sidebar will be on the page and when once he clicked on a toggle button(work to hide and show the sidebar).

It will hide and cookie will store that action and after refreshing the page sidebar will not be on the page that time. If he wants to see he can click on the button".

Mayur Prajapati
  • 5,454
  • 7
  • 41
  • 70
Arun Arya
  • 19
  • 2
  • 8
  • How to set / get cookies in Javascript: http://stackoverflow.com/questions/4825683/how-do-i-create-and-read-a-value-from-cookie . This should help you. – Webice Aug 13 '15 at 05:48

2 Answers2

2

Better would be to use localStorage for this sort of things, basically here's how to set and get data

localStorage.setItem('sidebar', 1); //sets value
localStorage.getItem('sidebar'); //gets value
localStorage.removeItem('sidebar'); //removes value

Why better: when cookie doesn't have expiry date, it will be deleted as soon as browser is closed, so setting expiry date on sidebar toggle is quite stupid thing, better would be to use localStorage as it doesn't have restrictions, and better API to use. All major browsers support it. Read more about localStorage

Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69
0

<!DOCTYPE html>
<html>
<head>
<script>

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}

function getCookie(cname) {
    var name = cname + "=";
    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);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}

</script>
</head>
<body onload="checkCookie()">
</body>
</html>

For better go this link:Link

Anand Dwivedi
  • 1,452
  • 13
  • 23