​I'm trying to do a regular post on useful javascript libraries and plugins to existing frameworks such as jQuery, knockoutJs etc...

​So to kick things off, let me introduce jquery.cookie. This usefully little library allows you to get and set cookies on the client side. Now why might you want to do this?

  • ​Serve up a generic cached page and personalize based on cookie information (a lot of sites do this, like eBay shows your name, but will still require you to sign in)
  • Retrieve some information via AJAX and save it to a cookie

​I've used this on several projects in the past, and it's nice and easy to use.

    <script src="/path/pto/jquery.cookie.js"></script>
    
    • .Set a cookie
    var userProfile = {
        Name: 'Eric Phan',
        Age: 28,
        LastLogin: '2013-04-22 11:24 PM' 
    };
    
    var cookieOptions = {
        expires: 7, // expire in 7 days	
        path: '/', // path of the cookie
        domain: 'ericphan.net', // domain the cookie is valid for
        secure: false // whether to transmit the cookie over HTTPS
    };
    
    // Need to store the JSON data as string
    $.cookie('UserProfile', JSON.stringify(userProfile), cookieOptions);
    
    • Get a cookie
    var cookie = $.cookie('UserProfile');
    
    // Convert the string value back to JSON
    var userProfileData = JSON.parse(cookie);
    
    console.log(userProfileData.Name)
    
    • Delete a cookie
    $.removeCookie('UserProfile', { path: '/', domain: 'ericphan.info'});
    

    ​Really simple and easy to use. Props to Klaus Hartl for developing such a handy little plugin.

    Comment