Search code examples
javascripthtmlcookiessetcookie

Check for Cookie existance, if yes do whatever, if no set a cookie


So what im tryin to do is to check for a cookie existance (for example accepted=yes) If it is not set, it will return nothing and if not, it will execute some script and set the accepted=yes cookie. So that on the next visit the visitor wont see the popup.

var cookie = document.cookie;
if (cookie = accepted=yes) {

} else {
    document.cookie = "accepted=yes";
}

That is the code i have discovered.


Solution

  • You can use getCookie and setCookie Functions

    function setCookie(cname, cvalue, exdays) {
      var d = new Date();
      d.setTime(d.getTime() + (exdays*24*60*60*1000));
      var expires = "expires="+ d.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 "";
    }
    

    Example

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

    Reference: W3Schools https://www.w3schools.com/js/tryit.asp?filename=tryjs_cookie_username