Logo

How do I set/unset a cookie with jQuery?

While jQuery doesn’t include a built-in method for managing cookies, you can handle them easily using either a third-party plugin (like the jQuery Cookie Plugin) or native JavaScript. Here’s how both approaches look:

1. Using the jQuery Cookie Plugin

You’ll first need to include the plugin on your page:

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js"></script>

Then, you can create and delete cookies as follows:

// Set a cookie $.cookie('myCookie', 'HelloWorld', { expires: 7 }); // 'expires: 7' means the cookie lasts for 7 days // Retrieve a cookie var cookieValue = $.cookie('myCookie'); console.log(cookieValue); // Output: HelloWorld // Remove a cookie $.removeCookie('myCookie');

Note: The plugin’s syntax uses $.cookie() to set or get cookies and $.removeCookie() to delete them.

2. Using Plain JavaScript in Conjunction with jQuery

If you don’t want to rely on a plugin, you can use vanilla JavaScript functions:

// Set a cookie function setCookie(name, value, days) { var expires = ''; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = '; expires=' + date.toUTCString(); } document.cookie = name + '=' + (value || '') + expires + '; path=/'; } // Get a cookie function getCookie(name) { var nameEQ = name + '='; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); } } return null; } // Delete a cookie function eraseCookie(name) { document.cookie = name + '=; Max-Age=-99999999;'; } // Usage with jQuery elements $('#setButton').on('click', function() { setCookie('myCookie', 'HelloWorld', 7); // Expires in 7 days }); $('#getButton').on('click', function() { alert(getCookie('myCookie')); }); $('#deleteButton').on('click', function() { eraseCookie('myCookie'); });

Using these plain JavaScript functions works seamlessly with jQuery event handlers (like click or change), and you don’t need any external libraries.

3. Best Practices

  1. Security: If your site is HTTPS, always mark cookies as Secure and consider using HttpOnly or SameSite flags on the server side for sensitive information.
  2. Naming: Use clear, descriptive names for your cookies to avoid confusion (e.g., userSession, cartItems, etc.).
  3. Expiry: Carefully set expires or Max-Age based on how long the data should remain valid.

Further Your JavaScript Skills

To truly master front-end development (including jQuery and advanced DOM manipulation), build a strong JavaScript foundation with:

  • Grokking JavaScript Fundamentals – Gain a robust understanding of modern JavaScript, covering everything from the basics of ES6 to asynchronous programming.

If you’re aiming to excel in technical interviews, Grokking the Coding Interview: Patterns for Coding Questions will familiarize you with common problem-solving patterns. And for one-on-one feedback from ex-FAANG engineers, explore Coding Mock Interviews at DesignGurus.io.

In a nutshell, you can manage cookies using a jQuery plugin for an out-of-the-box solution or rely on plain JavaScript for full control. Both approaches work well in tandem with jQuery, ensuring a smooth experience when setting, getting, or deleting cookies.

CONTRIBUTOR
TechGrind