Creating a Cookie using jQuery
In one of my projects, I was tasked to create a cookie (no, not the chocolate chip dough, but a browser cookie), and I had to do it using jQuery, a commonly used JavaScript library. It can be done using plain old JavaScript, of course, but life is so much better with jQuery! By definition, a browser cookie is a text file created by a web browser for every unique website or domain. The cookie can only be accessed on the same domain where it was originally created. To be able to create a cookie using jQuery, you need to include a plug-in that can be downloaded from GitHub.
Everything is already explained on the GitHub page, and the code is not very complicated. Perhaps, a few watch-outs would be:
Everything is already explained on the GitHub page, and the code is not very complicated. Perhaps, a few watch-outs would be:
- Differentiating between a session cookie and an expiring cookie. A session cookie is only valid until the user closes the web browser. An expiring cookie only gets removed after a specified number of days. Note: the unit of measure for the expires parameter is days.
- The path parameter specifies the accessibility of the cookie. A forward slash means the cookie can be accessed in the entire domain. If you want to limit the accessibility of the cookie to certain pages only, you can specify the relative path of the webpage in this parameter.
- Make sure that the domain parameter matches the last two tokens of your site's host name; otherwise, the cookie will not be created. If the domain name changes, for instance, when you transfer to another page, a new cookie of the same key will be created.
$.cookie(key, value, {
expires: 1,
path: '/',
domain: 'example.com'
}); - Another thing is that the value is always assumed to be a text type, not a JSON object. I think the value will be automatically boxed to JSON object using $.cookie.json = true as explained on the GitHub page, but I haven't really tried it. I have done the manual way using JSON.stringify and JSON.parse, but I think it is a better approach since there is more flexibility on the setting the value.
Comments
Post a Comment