Select Page

<script> 
//edited from w3schools.com
function createCookie(cref,cstring,clength) {
  var nD = new Date();
  nD.setTime(nD.getTime() + (clength*24*60*60*1000));
  var quitC = "quitC=" + nD.toGMTString();
  document.cookie = cref + "=" + cstring + ";" + quitC + ";path=/";
}

function newCookie() {
  setCookie("username", "Bradley", 365);
}
// from w3schools.com
function processgetCookie(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 getCookie() {
 var user=processgetCookie("username");
  if (user != "") {
    alert("Welcome again " + user);
  } else {
     user = prompt("Please enter your name:","");
     if (user != "" && user != null) {
       setCookie("username", user, 365);
     }
  }
}
</script>

<button class="button" onclick="createCookie("username", "Bradley", 365;">Set Cookie Direct From Function</button>
or
<button class="button" onclick="newCookie();">Set Cookie Through Other Function</button>
<hr />
<button class="button" onclick="getCookie();">Get Cookie Function</button>
or