How to Easily Manage Cookies Within jQuery

tutorial screenshot cookies with jQuery howto

Web browsers can generate unique sessions organized for each user on a website. Often these are handled on the backend using languages like PHP or Ruby, but we can also utilize cookie sessions on the frontend with Javascript. There are many tutorials out there explaining how to generate pure JS cookies. But a newer library jQuery Cookie simplifies the whole process.

I want to explain how we can build a very simple authentication system using jQuery Cookies. The code is all handled on the frontend but you will need a live testing server to see any results. Browser cookies are created on the local IP which comes from the web server, and so unfortunately you can’t just run these scripts locally. But definitely check out my live demo to get an idea of what we are creating.

Live DemoDownload Source Code

Document Base

First I am creating a sample HTML5 document with a single link to the jQuery library, along with the jQuery Cookies function. You can download this directly from the Github repo and the only file we need is jquery.cookie.js.

<!doctype html>
<html lang="en-US">
  <meta charset="utf-8">
  <meta http-equiv="Content-Type" content="text/html">
  <title>Managing Cookies with jQuery - Live Demo</title>
  <meta name="author" content="Jake Rocheleau">
  <link rel="shortcut icon" href="">
  <link rel="icon" href="">
  <link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
  <script type="text/javascript" src="js/jquery-1.10.2.min.js"></script>
  <script type="text/javascript" src="js/jquery.cookie.js"></script>

The tutorial itself will focus on creating two distinct views for the page. First we have a login form which displays when the cookie is not set. Using the default values of demo/demo you can log into the form and it will store your session in a cookie.

Obviously when connecting into a database you can pull from a large number of usernames. This means you can authenticate many people using the same script and storing their username or user ID into a local cookie. This example provides a starting point where we don’t need any Ajax requests or backend scripts to authenticate a user.

Inner Body Contents

The first containing div is a wrapper which holds all the rest of the page. There is a form with the ID #loginform which is first to display. This will be hidden using jQuery only if the visitor is currently logged into the demo account with a session cookie.

<div id="w">
  <div id="content">
    <h1>Basic Cookie Management</h1>
    <p>Login to the demo account with the following username/password: demo/demo</p>
    <form id="loginform" method="post" action="#">
      <label for="username">Username:</label>
      <input type="text" name="username" id="username" class="basic" placeholder="username...">
      <label for="password">Password:</label>
      <input type="password" name="password" id="password" class="basic">
      <input type="submit" name="submit" class="button" value="Login">
    </form><!-- @end #loginform -->
    <div id="logindetails">
      <!-- when user is logged in we display this div -->
      <p>You are logged in as <strong>demo</strong>! The cookie is set to expire in 1 day from the original login.</p>
      <p>Want to logout? Easy!</p>
      <p id="logoutcontainer"><a href="#" id="logoutbtn" class="button">Logout Now</a></p>
    </div><!-- @end #logindetails -->
  </div><!-- @end #content -->
</div><!-- @end #w -->

You will notice in the HTML after the login form there is another div with the ID #logindetails. I have this hidden using CSS styles because we only want this displaying to the user if they are currently authenticated. The internal HTML is static always displaying the username as demo – but when pulling from a database you can update this with JavaScript for any username.

The CSS styles are not too confusing but it is worth going over some pieces. I have built a glossy CSS3 button from this Codepen post which also has some other examples. The styles are quite in-depth but worth saving to possibly reuse on other websites.

/** form elements **/
form label { font-size: 1.1em; line-height: 1.25em; font-weight: bold; margin-bottom: 5px; }

form input.basic {
  display: block;
  outline: none;
  font-size: 1.5em;
  color: #525252;
  width: 300px;
  padding: 10px 8px 10px 8px;
  margin-bottom: 7px;
  border: 1px solid #888;
  border-radius: 5px;
  -webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,0.4);
  -moz-box-shadow: inset 0 1px 2px rgba(0,0,0,0.4);
  box-shadow: inset 0 1px 2px rgba(0,0,0,0.4);

#logindetails {
  display: none;

I also redesigned the basic form inputs to blend nicely into the page. The login details container is given display: none so it will not take up any room in the rendered page. However it is still an active part of the DOM which means we can manipulate this display value in jQuery. Now let’s look into this jQuery code located at the bottom of the page right before the closing </body> tag.

Cookies in jQuery

This plugin offers a number of standard features which would require a whole lot more logic in regular JavaScript. There are pre-built internal methods for calling a new cookie and deleting any existing one. We can look at the first opening code block to understand the displays:

$  (function(){
  if($  .cookie('username')) {
    $  ('#loginform').hide();
    $  ('#logindetails').show();

There is likely a better way to handle this form using backend languages, but jQuery works great for this demo. By calling an if statement against $ .cookie(‘username’) we are checking if the cookie “username” exists. If so then we know a user is currently logged into their account, so we hide the login form and show the login details. Otherwise nothing happens and we just see the page with the login form as it would normally appear.

  $  ('#loginform').submit(function(e){
    var inputuname = $  ('#username').val();
    var inputpass  = $  ('#password').val();
    if(inputuname == "demo" && inputpass == "demo") {
      // successful validation and create cookie
      $  .cookie('username', 'demo', { expires: 1 });
      var currentusr = $  .cookie('username');
  $  ('#logoutbtn').on('click', function(e){
    if($  .removeCookie('username')) {
      $  ('#logoutcontainer').html('<strong>Successfully logged out! Refreshing the page now...</strong>');
      window.setTimeout('location.reload()', 2000); // refresh after 2 sec

I’ve combined these two functions into a single block of code because they are closely related. Once the user attempts to log into an account we make sure the username/password is equal to “demo”. If successful then we call $ .cookie(‘username’, ‘demo’, { expires: 1 }); which includes a number of options.

First we set the cookie name to “username” which is how we can check its value. The string “demo” is the value of this cookie, but remember we could pass any username or even an ID string if that works better. Finally the last parameter is a collection of options which sets the number of days before the cookie would expire. If we omit the expires option then the cookie will be deleted once the user closes out of their browsing session. This is also referred to as a session cookie and I’ve written a basic example commented out at the bottom of the script.

The second code block is listening for a user to click on the #logoutbtn link. Naturally the logout link will only display when the current visitor is already logged in. This function will terminate the session by calling $ .removeCookie(‘username’) inside an if statement. So if we can delete the cookie, then we remove the logout button to show a success message followed by a refresh to present the original login form again.

Live DemoDownload Source Code

Final Thoughts

Cookies are very helpful even aside from storing logins to various user accounts. You can organize an ecommerce website based on backend sessions with a unique cookie ID. Shopping carts are so popular nowadays and the advancements in web development have made them much easier to setup. Feel free to download a sample copy of my script and see if you can implement live cookies on any of your own web projects.

Design Shack

Leave a Comment