Open In App

How to set and unset cookies using jQuery?

Improve
Improve
Like Article
Like
Save
Share
Report

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 own 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




<!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>


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:



Last Updated : 01 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads