Setting cookies in jQuery typically requires additional libraries because native jQuery does not support direct cookie manipulation. We commonly use the jquery.cookie plugin to simplify this process. First, ensure that you have included the jQuery library and the jquery.cookie plugin.
Setting Cookie Expiration Time
To set a cookie to expire after 1 minute or 30 seconds, use the $.cookie function with the expires option, which defines the cookie's lifespan in days. For minutes or seconds, calculate the expiration time using the Date object.
Setting Cookie to Expire After 1 Minute
javascript// First, ensure the jQuery library and `jquery.cookie` plugin are included // <script src="path/to/jquery.js"></script> // <script src="path/to/jquery.cookie.js"></script> $(document).ready(function() { var date = new Date(); date.setTime(date.getTime() + (1 * 60 * 1000)); // Time one minute from now $.cookie('cookie_name', 'cookie_value', { expires: date }); });
Setting Cookie to Expire After 30 Seconds
javascript$(document).ready(function() { var date = new Date(); date.setTime(date.getTime() + (30 * 1000)); // Time 30 seconds from now $.cookie('cookie_name', 'cookie_value', { expires: date }); });
Important Note
When using the expires option, passing a Date object ensures millisecond precision, allowing specific expiration times like 30 seconds or 1 minute. Additionally, verify that jQuery and the jquery.cookie plugin are loaded before setting cookies; otherwise, the code will fail. This approach enables flexible cookie expiration for temporary data storage scenarios.