Before using jQuery to set or remove cookies, ensure that you have included the jQuery library and the jQuery Cookie plugin, as jQuery does not natively support direct cookie manipulation. You can find the jQuery Cookie plugin on jsDelivr or other CDNs.
Include the Libraries
First, include jQuery and the jQuery Cookie plugin in your HTML file:
html<!-- Include jQuery --> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <!-- Include jQuery Cookie plugin --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
Set a Cookie
Setting a cookie with the jQuery Cookie plugin is straightforward. For example, to set a cookie for a user's login status, you can do the following:
javascript// Set a cookie $.cookie('user', 'Zhang San', { expires: 7, path: '/' });
In this example, 'user' is the cookie name, 'Zhang San' is the stored value, and { expires: 7, path: '/' } is an object specifying additional cookie properties, such as expiration time (expires after 7 days) and path (valid across the entire site).
Read a Cookie
Reading an existing cookie is equally simple:
javascript// Read a cookie var user = $.cookie('user'); console.log(user); // Output: Zhang San
Remove a Cookie
To delete a cookie, simply call the $.removeCookie() function and pass the cookie name to be removed:
javascript// Remove a cookie $.removeCookie('user', { path: '/' });
Here, { path: '/' } is required because the path was specified when setting the cookie, and it must be specified again when deleting.
Example: User Login and Logout
Consider a practical scenario where a cookie is set upon user login and removed upon logout.
javascript// User login function login(username) { $.cookie('user', username, { expires: 7, path: '/' }); console.log(username + ' has logged in'); } // User logout function logout() { $.removeCookie('user', { path: '/' }); console.log('User has logged out'); } // Usage login('Zhang San'); logout();
This covers how to set, read, and remove cookies using the jQuery Cookie plugin within jQuery. This approach is very useful for handling persistent user preferences, login states, and similar scenarios.