jQuery Cookie Plugin
I’ve been using the jquery cookie plugin created an age ago by Klaus Hartl (stilbuero.de) but it looks like his site is down? It’s a very easy to use plugin – not all that complicated but I thought I’d post our couple of most basic uses here since we had to use it recently and I couldn’t find the demos:
Pre-reqs – load jquery first and then the cookie plugin:
<script src="PATH-TO-JQUERY/jquery-1.4.2.min.js"></script> <script src="PATH-TO-JQUERY/jquery.cookie.js"></script>
Most used – example for a one time user notification via js…
var MESSAGE_COOKIE_NAME = 'sawMessage'; // code for the cookie name $(document).ready(function(){ var sawMessage = false; if (typeof $.cookie != 'undefined'){ sawMessage = ($.cookie(MESSAGE_COOKIE_NAME) == '1'); } if (!sawMessage){ $.cookie(MESSAGE_COOKIE_NAME, '1', { path: '/', domain: 'mydomain.com', expires: 365 }); // expires in one year // code to show the message } }
Used less often – a cookie for just 1 session:
if (typeof $.cookie != 'undefined'){
// set it
$.cookie('one-session-cookie', 'yes');
// read it
if ($.cookie('one-session-cookie') == 'yes'){
alert('the cookie was set');
}
}
