There are a number of ways cookies can enhance the user experience on your website or in your app, which i’ll not get into here but will cover in the future.¬†For the time being lets look at how we can set cookies in our application using a jQuery plugin.

jQuery Cookie plugin

The first thing you need to do is head over the Github and grab the jQuery-cookie plugin – this plugin provides all the functionality you’ll need to implement cookies swiftly and with minimum fuss.

https://github.com/carhartl/jquery-cookie

Once you’ve downloaded the plugin extract the contents and grab the jQuery-cookie.js file and drop it into your scripts directory.

Then add the following reference to the file in your <head> section.

Now we can go ahead and set a cookie with a value using this jQuery cookie plugin, like so:

So we’ve just set a cookie called ‘test’ with the value of ‘100’

Deleting a cookie is just as easy:

Another common practice is to set an expiry time for the cookie, so that it expires after x days. Worth noting that this value must be set if you want the cookie to exist after the current session expires. Without this value the cookie will expire along with the browser session! Again, very easy to achieve with the jQuery Cookie plugin:

Finally there’s a couple other options available which are less common but i’ll pop them here anyway for reference.

 

Leave a Reply