
How do I set/unset a cookie with jQuery
To set or unset a cookie using jQuery, you need to use the jquery.cookie
plugin, as jQuery itself does not have built-in cookie management functions. Here’s how you can do it:
Setting a Cookie
To set a cookie, you use the $.cookie()
function. Here is an example:
$.cookie('cookie_name', 'cookie_value', { expires: 7, path: '/' });
In this example:
cookie_name
is the name of the cookie.cookie_value
is the value you want to store in the cookie.- The options object can include parameters like
expires
(number of days until the cookie expires),path
(the path where the cookie is accessible), anddomain
(the domain where the cookie is accessible)235.
Reading a Cookie
To read a cookie, you pass only the name of the cookie to the $.cookie()
function:
var cookieValue = $.cookie('cookie_name');
console.log(cookieValue); // Prints the value of the cookie
Unsetting or Deleting a Cookie
To delete a cookie, you use the $.removeCookie()
function. Here is an example:
$.removeCookie('cookie_name', { path: '/', domain: 'example.com' });
When deleting a cookie, you must pass the same options (such as path
and domain
) that were used when the cookie was created to ensure the operation succeeds235.
Example
Here’s a complete example of setting, reading, and deleting a cookie using jQuery with the jquery.cookie
plugin:
// Set a cookie
$.cookie('name', 'Peter', { expires: 7, path: '/' });
// Read the cookie
var cookieValue = $.cookie('name');
console.log(cookieValue); // Prints: Peter
// Delete the cookie
$.removeCookie('name', { path: '/' });
Make sure to include the jquery.cookie.js
file after the jQuery library in your HTML:
<head>
<script src="path/to/jquery.js"></script>
<script src="path/to/jquery.cookie.js"></script>
</head>
This setup allows you to manage cookies efficiently using jQuery.