Skip to content

Instantly share code, notes, and snippets.

@luckyshot
Last active May 14, 2020 11:01
Show Gist options
  • Select an option

  • Save luckyshot/5630441 to your computer and use it in GitHub Desktop.

Select an option

Save luckyshot/5630441 to your computer and use it in GitHub Desktop.
Cookie JavaScript object methods
/**
* CRUD cookies
* expires is in Days
*/
var _cookieSet = function( name, value, expires, path, domain, secure )
{
var today = new Date(),
expires_date;
today.setTime( today.getTime() );
if ( expires )
{
expires = expires * 1000 * 60 * 60 * 24;
}
expires_date = new Date( today.getTime() + ( expires ) );
document.cookie = name + '=' + encodeURIComponent( value ) +
( ( expires ) ? ';expires=' + expires_date.toGMTString() : '' ) + //expires.toGMTString()
( ( path ) ? ';path=' + path : '' ) +
( ( domain ) ? ';domain=' + domain : '' ) +
( ( secure ) ? ';secure' : '' );
};
var _cookieGet = function( name )
{
var ca = document.cookie.split(';'),
nameEQ = name + "=",
i = 0,
c;
for ( ; i < ca.length; i++ )
{
c = ca[i];
while ( c.charAt(0) === ' ' )
{
c = c.substring( 1, c.length );
} // delete spaces
if ( c.indexOf( nameEQ ) === 0 )
{
return decodeURIComponent( c.substring( nameEQ.length, c.length ) );
}
}
return null;
};
// Examples
cookie.set( 'param', 1, 7 );
cookie.get( 'param' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment