Skip to content

Instantly share code, notes, and snippets.

@markshust
Last active August 29, 2015 14:11
Show Gist options
  • Select an option

  • Save markshust/417966defa3e955fbe79 to your computer and use it in GitHub Desktop.

Select an option

Save markshust/417966defa3e955fbe79 to your computer and use it in GitHub Desktop.
Create a cookie with JavaScript
/**
* Creates a cookie
*
* If expiresVal is null, only create session cookie
* ExpiresType is either y, d, h, or m (years, days, minutes or hours)
*
* @param name
* @param value
* @param expiresVal
* @param expiresType
*/
function createCookie(name, value, expiresVal, expiresType) {
var date = new Date(),
expires = '',
offset = 0;
if (expiresVal) {
switch (expiresType) {
case 'm': // minutes
{
offset = expiresVal * 60 * 1000;
break;
}
case 'h': // hours
{
offset = expiresVal * 60 * 60 * 1000;
break;
}
case 'y': // years
{
offset = expiresVal * 365 * 24 * 60 * 60 * 1000;
break;
}
default: // days
{
offset = expiresVal * 24 * 60 * 60 * 1000;
break;
}
}
date.setTime(date.getTime() + offset);
expires = ';expires=' + date.toGMTString();
}
document.cookie = name + '=' + value + expires + ';path=/';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment