How to set and unset cookies using jQuery?

An HTTP cookie is a small piece of data sent from a server and stored on client-side by the browser itself, Cookies are made to keep track of user and also to provide one nice browsing experience. We can also set our on cookies in the browser according to our need.

Cookies can be set in the browser with the help of JavaScript or the jQuery. Here we will be seeing how to set cookies in the browser with the help of jQuery and how to remove them later on.

Here we are using CDN of jQuery cookies to insert a cookie in the browser .

Note: Please keep your internet connection on while using this code as it uses CDN services for jQuery.

Example 1: Setting cookies in the  browser after that we will remove that cookie.



HTML

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport"
            content="width=device-width, initial-scale=1.0">
      <title>Cookie | Geeksforgeeks</title>
      <script src=
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
         crossorigin= "anonymous"></script>
      <script src=
   </head>
   <body>
      <center>  
        <h1 style="color: green">GeeksforGeeks</h1>
        <button onclick="addCookie()">
        Add Cookie
        </button>
        <button onclick="removeCookie()">
        remove Cookie
        </button>
          
<p></p>
  
        <script>
            let addCookie=()=>{
            $.cookie("geeksforgeeks", 
            "It is the data of the cookie");
            $("p").text("cookie added");
            }
            let removeCookie=()=>{
            $.removeCookie("geeksforgeeks", 
            "It is the data of the cookie");
            $("p").text("cookie removed");
            }
        </script>
      </center>
   </body>
</html>

chevron_right


Output: You can clearly see there is a cookie named GeeksforGeeks with a value. We can also set the cookie Expiry date.

  • Before adding Cookie: 

  • After adding Cookies:

  • After removing Cookie:




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.