X

LATEST #JQUERY NEWS

Set/Get/Delete Cookies with jQuery


There are a lot of plugins you can use to set, get, and delete cookies using jQuery, but there’s also a fairly simple code that will achieve all three of those actions without the need for a heavy plugin. Check out the snippets below:

Set cookies:

function setCookie( name, value, expires, path, domain, secure ) {
 var today = new Date();
 today.setTime( today.getTime() );
 if ( expires ) {
 expires = expires * 1000 * 60 * 60 * 24;
 }
 var expires_date = new Date( today.getTime() + (expires) );
 document.cookie = name+'='+escape( value ) +
 ( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
 ( ( path ) ? ';path=' + path : '' ) +
 ( ( domain ) ? ';domain=' + domain : '' ) +
 ( ( secure ) ? ';secure' : '' );
}

Get cookies:

 function getCookie( name ) { 
 var start = document.cookie.indexOf( name + "=" );
 var len = start + name.length + 1;
 if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
 return null;
 }
 if ( start == -1 ) return null;
 var end = document.cookie.indexOf( ';', len );
 if ( end == -1 ) end = document.cookie.length;
 return unescape( document.cookie.substring( len, end ) );
}

Delete cookies:

function deleteCookie( name, path, domain ) {
 if ( getCookie( name ) ) document.cookie = name + '=' +
 ( ( path ) ? ';path=' + path : '') +
 ( ( domain ) ? ';domain=' + domain : '' ) +
 ';expires=Thu, 01-Jan-1970 00:00:01 GMT';
}

Recently Published

article image
»

How to Use Google Analytics with jQuery Mobile

jQuery Mobile is an HTML5 based web-page framework that’s ...

article image
»

jQuery Snippets: Using jQuery to Check All Boxes

When you’ve given your users a ton of┬ácheckbox input fields ...

article image
»

Useful jQuery Code Snippets for Working with Images

Images are an essential part of any website and sometimes working ...

article image
»

How to Use jQuery to Check if Cookies are Enabled

A cookie (not the kind with chocolate chips) is a small piece of data ...

article image
»

A Beginner’s Guide to jQuery’s Selectors

We talk a lot about event methods on this site, but not so much about ...

article image
»

Add Keyboard Shortcut to Anchor Tag Using jQuery

Making a user friendly website can be quite a challenging task. There ...

Screen Shot 2017-04-23 at 10.15.41 AM
»

How to Use jQuery to Create a Sticky Navigation on Scroll

Creating “sticky” elements is something that can often be ...

article image
»

How to Use jQuery’s Keystroke Methods

jQuery has a few built-in keystroke methods that are all triggered by ...

article image
»

How to Change iFrame Styling Using jQuery

If you’ve ever had the displeasure of working with iFrames, ...