Home >Web Front-end >JS Tutorial >How to Set and Unset Cookies with (and Without) jQuery?

How to Set and Unset Cookies with (and Without) jQuery?

DDD
DDDOriginal
2024-12-31 09:40:10641browse

How to Set and Unset Cookies with (and Without) jQuery?

Setting and Unsetting Cookies with jQuery

Question:

How to set/unset a cookie using jQuery?

Answer:

Update (April 2019)

For cookie manipulation, jQuery is no longer necessary. Refer to https://github.com/js-cookie/js-cookie for a library that accomplishes this task without jQuery.

Example:

// Set a cookie
Cookies.set('name', 'value');

// Read the cookie
Cookies.get('name') => 'value'

Pre-April 2019 (deprecated)

Utilize the jQuery-Cookie plugin: https://github.com/carhartl/jquery-cookie.

Example:

Set a cookie:
$.cookie("test", 1);

Delete a cookie:
$.removeCookie("test");

Configure cookie parameters:

$.cookie("test", 1, {
  expires: 10, // Expires in 10 days
  path: "/",
  domain: "jquery.com",
  secure: true
});

Read a cookie:

var cookieValue = $.cookie("test");

Update (April 2015)

Alternately, consider https://github.com/js-cookie/js-cookie, which provides similar functionality without a jQuery dependency.

The above is the detailed content of How to Set and Unset Cookies with (and Without) jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn