Skip to content

Instantly share code, notes, and snippets.

@ghostwriter
Created February 4, 2016 20:15
Show Gist options
  • Save ghostwriter/1f43edb6b94bb8e587a9 to your computer and use it in GitHub Desktop.
Save ghostwriter/1f43edb6b94bb8e587a9 to your computer and use it in GitHub Desktop.
Simple, no-dependency JavaScript to GET, SET and DELETE cookies
function getCookie(name) {
var cname = 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);
if (c.indexOf(cname) == 0)
return c.substring(cname.length, c.length);
}
return "";
}
function setCookie(name, value, days) {
var t = new Date();
t.setDate(t.getDate() + days);
document.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) + '; expires=' + t.toUTCString() + '; path=/';
}
function deleteCookie(name) {
// value is an empty string
document.cookie = encodeURIComponent(name) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT; path=/';
};
function deleteCookie_alt(name) {
setCookie(name, '', -1);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment