JavaScript Cookies – How to Create a Cookie? – Cookie Attributes

What is Cookie in JavaScript?

A cookie in JavaScript is like a little piece of information that a website stores on your computer when you visit it. It’s like a note that the website writes to remember certain things about you, such as your preferences or login information. Cookies can be helpful because they allow websites to recognize you when you come back, so you don’t have to re-enter your information every time. However, they can also be used for tracking your online activities, so it’s important to understand how they work and how to manage them.

How Cookies Works?

Cookies work like a note that a website leaves on your computer. When you visit a website, it sends a cookie to your browser, which your browser then saves. This cookie contains information that the website wants to remember, such as your preferences or login information.

When you visit the website again, your browser sends the cookie back to the website. This allows the website to recognize you and remember your previous interactions. For example, if you logged into a website and then return later, the website can use the cookie to remember that you’re already logged in.

Cookies can also be used for tracking your online activities. For example, a website might use cookies to see which pages you visit most often or to show you targeted advertisements based on your browsing history.

Overall, cookies are a useful tool for both websites and users, as they can help personalize your online experience. However, it’s important to be aware of how cookies are used and to manage them properly to protect your privacy.

How to create a Cookie in JavaScript?

  1. Decide What Information You Want to Store: Before creating a cookie, decide what information you want to store. For example, you might want to store a user’s name or preferences.

2.Set the Cookie: To set a cookie, you use the document.cookie property in JavaScript. This property holds a string with all the cookies associated with the current document.

document.cookie = "name=John Doe; expires=Thu, 18 Dec 2023 12:00:00 UTC; path=/";
    • In above example, name is the name of the cookie, and John Doe is the value.
    • The expires attribute specifies when the cookie will expire and be automatically deleted by the browser.
    • The path attribute specifies the path on the server for which the cookie is valid.

    3. Retrieve the Cookie: To retrieve the value of a cookie, you can use the document.cookie property again.

    let cookieValue = document.cookie;

    This will return a string containing all the cookies associated with the current document.

    4. Use the Cookie: Once you have retrieved the cookie value, you can use it in your JavaScript code. For example, you might display the user’s name on the webpage. (check code below)

    console.log("Hello, " + cookieValue);

    5. Remember to Manage Cookies: It’s important to manage cookies properly to protect user privacy. This includes setting appropriate expiration dates and using secure methods to transmit sensitive information.

      That’s it! You’ve now created a cookie in JavaScript to store and retrieve information. Remember to use cookies responsibly and comply with privacy regulations.

      JavaScript Cookie Real Time Example:

      <!DOCTYPE html>  
      <html>
      <head>
      </head>
      <body>
      <input type="button" value="setCookie" onclick="setCookie()">
      <input type="button" value="getCookie" onclick="getCookie()">
      <script>
      function setCookie()
      {
      document.cookie="username=Duke Martin";
      }
      function getCookie()
      {
      if(document.cookie.length!=0)
      {
      alert(document.cookie);
      }
      else
      {
      alert("Cookie not available");
      }
      }
      </script>

      </body>
      </html>

      Explanation of Above Code:

      1. <!DOCTYPE html>: Declares the document type and version of HTML (HTML5 in this case).
      2. <html>: The root element of an HTML page, containing all other elements.
      3. <head>: Contains meta-information about the document, such as its title and links to external resources.
      4. </head>: Closes the <head> element.
      5. <body>: Contains the content of the document that is visible to the user.
      6. <input type="button" value="setCookie" onclick="setCookie()">: Creates a button with the label “setCookie” that, when clicked, calls the setCookie() function defined in the <script> tag.
      7. <input type="button" value="getCookie" onclick="getCookie()">: Creates a button with the label “getCookie” that, when clicked, calls the getCookie() function defined in the <script> tag.
      8. <script>: Starts a JavaScript block.
      9. function setCookie() { document.cookie="username=Duke Martin"; }: Defines a function setCookie() that sets a cookie named “username” with the value “Duke Martin”.
      10. function getCookie() { if(document.cookie.length!=0) { alert(document.cookie); } else { alert("Cookie not available"); } }: Defines a function getCookie() that checks if any cookies are set. If cookies are present, it displays an alert with the cookie value. If no cookies are present, it displays an alert saying “Cookie not available”.
      11. </script>: Closes the JavaScript block.
      12. </body>: Closes the <body> element.
      13. </html>: Closes the <html> element, indicating the end of the HTML document.

      This HTML document demonstrates basic cookie handling using JavaScript. The setCookie() function sets a cookie when the “setCookie” button is clicked, and the getCookie() function retrieves and displays the cookie value when the “getCookie” button is clicked.

      Let’s Take another Example:

      In the below example we will display the cookie’s name-value pair separately.

      <!DOCTYPE html>  
      <html>
      <head>
      </head>
      <body>
      <input type="button" value="setCookie" onclick="setCookie()">
      <input type="button" value="getCookie" onclick="getCookie()">
      <script>
      function setCookie()
      {
      document.cookie="username=Duke Martin";
      }
      function getCookie()
      {
      if(document.cookie.length!=0)
      {
      var array=document.cookie.split("=");
      alert("Name="+array[0]+" "+"Value="+array[1]);
      }
      else
      {
      alert("Cookie not available");
      }
      }
      </script>

      </body>
      </html>

      Explanation of above code:

      1. <!DOCTYPE html>: Declares the document type and version of HTML (HTML5 in this case).
      2. <html>: The root element of an HTML page, containing all other elements.
      3. <head>: Contains meta-information about the document, such as its title and links to external resources.
      4. </head>: Closes the <head> element.
      5. <body>: Contains the content of the document that is visible to the user.
      6. <input type="button" value="setCookie" onclick="setCookie()">: Creates a button with the label “setCookie” that, when clicked, calls the setCookie() function defined in the <script> tag.
      7. <input type="button" value="getCookie" onclick="getCookie()">: Creates a button with the label “getCookie” that, when clicked, calls the getCookie() function defined in the <script> tag.
      8. <script>: Starts a JavaScript block.
      9. function setCookie() { document.cookie="username=Duke Martin"; }: Defines a function setCookie() that sets a cookie named “username” with the value “Duke Martin”.
      10. function getCookie() { if(document.cookie.length!=0) { var array=document.cookie.split("="); alert("Name="+array[0]+" "+"Value="+array[1]); } else { alert("Cookie not available"); } }: Defines a function getCookie() that checks if any cookies are set. If cookies are present, it splits the cookie string into an array at the “=” sign, and displays an alert showing the name and value of the cookie. If no cookies are present, it displays an alert saying “Cookie not available”.
      11. </script>: Closes the JavaScript block.
      12. </body>: Closes the <body> element.
      13. </html>: Closes the <html> element, indicating the end of the HTML document.

      This HTML document demonstrates basic cookie handling using JavaScript. The setCookie() function sets a cookie when the “setCookie” button is clicked, and the getCookie() function retrieves and displays the cookie value when the “getCookie” button is clicked.

      Here’s one for example so that you can practice:

      In this example, we offer a selection of colors and save the chosen color in a cookie. This cookie retains the user’s last color choice in their browser. Therefore, when the webpage is reloaded, the user’s previous color selection is displayed on the screen.

      <!DOCTYPE html>  
      <html>
      <head>
      </head>
      <body>
      <select id="color" onchange="display()">
      <option value="Select Color">Select Color</option>
      <option value="yellow">Yellow</option>
      <option value="green">Green</option>
      <option value="red">Red</option>
      </select>
      <script type="text/javascript">
      function display()
      {
      var value = document.getElementById("color").value;
      if (value != "Select Color")
      {
      document.bgColor = value;
      document.cookie = "color=" + value;
      }
      }
      window.onload = function ()
      {
      if (document.cookie.length != 0)
      {
      var array = document.cookie.split("=");
      document.getElementById("color").value = array[1];
      document.bgColor = array[1];
      }
      }


      </script>
      </body>
      </html>
      1. <!DOCTYPE html>: Declares the document type and version of HTML (HTML5 in this case).
      2. <html>: The root element of an HTML page, containing all other elements.
      3. <head>: Contains meta-information about the document, such as its title and links to external resources.
      4. </head>: Closes the <head> element.
      5. <body>: Contains the content of the document that is visible to the user.
      6. <select id="color" onchange="display()">: Creates a dropdown select element with an id of “color” and calls the display() function when the selection changes.
      7. <option value="Select Color">Select Color</option>: Creates an option in the select element with the value “Select Color” and the display text “Select Color”.
      8. <option value="yellow">Yellow</option>: Creates an option in the select element with the value “yellow” and the display text “Yellow”.
      9. <option value="green">Green</option>: Creates an option in the select element with the value “green” and the display text “Green”.
      10. <option value="red">Red</option>: Creates an option in the select element with the value “red” and the display text “Red”.
      11. </select>: Closes the select element.
      12. <script type="text/javascript">: Starts a JavaScript block.
      13. function display(): Defines a function display() that is called when the select element’s value changes.
      14. var value = document.getElementById("color").value;: Retrieves the selected value from the select element with the id “color”.
      15. if (value != "Select Color"): Checks if the selected value is not equal to “Select Color”.
      16. document.bgColor = value;: Sets the background color of the document to the selected color.
      17. document.cookie = "color=" + value;: Sets a cookie named “color” with the selected color value.
      18. window.onload = function (): Defines an onload event handler that runs when the window is fully loaded.
      19. var array = document.cookie.split("=");: Splits the cookie string at the “=” sign and stores the parts in an array.
      20. document.getElementById("color").value = array[1];: Sets the selected value of the select element to the value stored in the cookie.
      21. document.bgColor = array[1];: Sets the background color of the document to the value stored in the cookie.
      22. </script>: Closes the JavaScript block.
      23. </body>: Closes the <body> element.
      24. </html>: Closes the <html> element, indicating the end of the HTML document.

      This HTML document creates a dropdown select element for choosing colors and uses JavaScript to change the background color of the document based on the selected color. It also stores the selected color in a cookie to remember the choice when the page is reloaded.

      Cookie Attributes

      Cookie attributes are additional settings that you can apply to cookies to control how they behave. These attributes include things like the cookie’s expiration date, whether it should only be sent over secure connections (like HTTPS), and what path or domain the cookie is associated with.

      Here’s a breakdown of common cookie attributes:

      1. Expires/Max-Age: Sets the expiration date for the cookie. Once the expiration date is reached, the cookie is no longer stored by the browser.
      2. Secure: Indicates that the cookie should only be sent over secure connections (HTTPS).
      3. HttpOnly: Specifies that the cookie is not accessible via JavaScript, which helps prevent certain types of attacks, such as cross-site scripting (XSS).
      4. SameSite: Controls when cookies are sent in cross-origin requests. It helps mitigate cross-site request forgery (CSRF) attacks.
      5. Domain: Specifies the domain for which the cookie is valid. By default, cookies are only valid for the domain they originated from.
      6. Path: Specifies the path within the domain for which the cookie is valid. This allows you to limit the cookie to specific parts of your website.

      These attributes allow you to customize how cookies are used and provide additional security and control over your website’s data.

      Example of Cookie Attribute:

      <!DOCTYPE html>  
      <html>
      <head>
      </head>
      <body>
      <input type="button" value="setCookie" onclick="setCookie()">
      <input type="button" value="getCookie" onclick="getCookie()">
      <script>
      function setCookie()
      {
      document.cookie="username=Duke Martin;expires=Sun, 20 Aug 2030 12:00:00 UTC";
      }
      function getCookie()
      {
      if(document.cookie.length!=0)
      {
      var array=document.cookie.split("=");
      alert("Name="+array[0]+" "+"Value="+array[1]);
      }
      else
      {
      alert("Cookie not available");
      }
      }
      </script>
      </body>
      </html>
      1. <!DOCTYPE html>: Declares the document type and version of HTML (HTML5 in this case).
      2. <html>: The root element of an HTML page, containing all other elements.
      3. <head>: Contains meta-information about the document, such as its title and links to external resources.
      4. </head>: Closes the <head> element.
      5. <body>: Contains the content of the document that is visible to the user.
      6. <input type="button" value="setCookie" onclick="setCookie()">: Creates a button with the label “setCookie” that, when clicked, calls the setCookie() function defined in the <script> tag.
      7. <input type="button" value="getCookie" onclick="getCookie()">: Creates a button with the label “getCookie” that, when clicked, calls the getCookie() function defined in the <script> tag.
      8. <script>: Starts a JavaScript block.
      9. function setCookie(): Defines a function setCookie() that is called when the “setCookie” button is clicked.
      10. document.cookie="username=Duke Martin;expires=Sun, 20 Aug 2030 12:00:00 UTC";: Sets a cookie named “username” with the value “Duke Martin” and an expiration date of Sunday, 20th August 2030 at 12:00:00 UTC.
      11. function getCookie(): Defines a function getCookie() that is called when the “getCookie” button is clicked.
      12. if(document.cookie.length!=0): Checks if the length of the cookie string is not equal to 0, meaning there are cookies stored.
      13. var array=document.cookie.split("=");: Splits the cookie string at the “=” sign and stores the parts in an array.
      14. alert("Name="+array[0]+" "+"Value="+array[1]);: Displays an alert with the name and value of the cookie.
      15. else: Indicates what to do if there are no cookies stored.
      16. alert("Cookie not available");: Displays an alert indicating that there are no cookies available.
      17. </script>: Closes the JavaScript block.
      18. </body>: Closes the <body> element.
      19. </html>: Closes the <html> element, indicating the end of the HTML document.

      This HTML document demonstrates how to set and retrieve cookies using JavaScript. The setCookie() function sets a cookie with an expiration date, and the getCookie() function retrieves and displays the cookie’s name and value.

      Cookie max-age attribute:

      <!DOCTYPE html>  
      <html>
      <head>
      </head>
      <body>
      <input type="button" value="setCookie" onclick="setCookie()">
      <input type="button" value="getCookie" onclick="getCookie()">
      <script>
      function setCookie()
      {
      document.cookie="username=Duke Martin;max-age=" + (60 * 60 * 24 * 365) + ";"
      }
      function getCookie()
      {
      if(document.cookie.length!=0)
      {
      var array=document.cookie.split("=");
      alert("Name="+array[0]+" "+"Value="+array[1]);
      }
      else
      {
      alert("Cookie not available");
      }
      }
      </script>
      </body>
      </html>

      Explanation of above code:

      1. <!DOCTYPE html>: Declares the document type and version of HTML (HTML5 in this case).
      2. <html>: The root element of an HTML page, containing all other elements.
      3. <head>: Contains meta-information about the document, such as its title and links to external resources.
      4. </head>: Closes the <head> element.
      5. <body>: Contains the content of the document that is visible to the user.
      6. <input type="button" value="setCookie" onclick="setCookie()">: Creates a button with the label “setCookie” that, when clicked, calls the setCookie() function defined in the <script> tag.
      7. <input type="button" value="getCookie" onclick="getCookie()">: Creates a button with the label “getCookie” that, when clicked, calls the getCookie() function defined in the <script> tag.
      8. <script>: Starts a JavaScript block.
      9. function setCookie(): Defines a function setCookie() that is called when the “setCookie” button is clicked.
      10. document.cookie="username=Duke Martin;max-age=" + (60 * 60 * 24 * 365) + ";": Sets a cookie named “username” with the value “Duke Martin” and a maximum age of one year (60 seconds * 60 minutes * 24 hours * 365 days).
      11. function getCookie(): Defines a function getCookie() that is called when the “getCookie” button is clicked.
      12. if(document.cookie.length!=0): Checks if the length of the cookie string is not equal to 0, meaning there are cookies stored.
      13. var array=document.cookie.split("=");: Splits the cookie string at the “=” sign and stores the parts in an array.
      14. alert("Name="+array[0]+" "+"Value="+array[1]);: Displays an alert with the name and value of the cookie.
      15. else: Indicates what to do if there are no cookies stored.
      16. alert("Cookie not available");: Displays an alert indicating that there are no cookies available.
      17. </script>: Closes the JavaScript block.
      18. </body>: Closes the <body> element.
      19. </html>: Closes the <html> element, indicating the end of the HTML document.

      This HTML document demonstrates how to set a cookie with a maximum age and retrieve its value using JavaScript.

      Cookie with multiple Name-Value pairs:

      A cookie with multiple name-value pairs is like having a box of cookies with different flavors. Each cookie (name-value pair) has its own unique flavor (value) and label (name). Just as you can have a variety of cookies in one box, a cookie with multiple name-value pairs allows you to store different pieces of information (values) under different labels (names) in a single cookie. This helps websites remember more about your preferences and activities, making your browsing experience more personalized.

      For example:

      <!DOCTYPE html>  
      <html>
      <head>
      </head>
      <body>
      Name: <input type="text" id="name"><br>
      Email: <input type="email" id="email"><br>
      Course: <input type="text" id="course"><br>
      <input type="button" value="Set Cookie" onclick="setCookie()">
      <input type="button" value="Get Cookie" onclick="getCookie()">
      <script>
      function setCookie()
      {
      //Declaring 3 key-value pairs
      var info="Name="+ document.getElementById("name").value+";Email="+document.getElementById("email").value+";Course="+document.getElementById("course").value;
      //Providing all 3 key-value pairs to a single cookie
      document.cookie=info;
      }

      function getCookie()
      {
      if(document.cookie.length!=0)
      {
      //Invoking key-value pair stored in a cookie
      alert(document.cookie);
      }
      else
      {
      alert("Cookie not available")
      }
      }
      </script>
      </body>
      </html>

      Explanation of above code:

      1. <!DOCTYPE html>: Declares the document type and version of HTML (HTML5 in this case).
      2. <html>: The root element of an HTML page, containing all other elements.
      3. <head>: Contains meta-information about the document, such as its title and links to external resources.
      4. </head>: Closes the <head> element.
      5. <body>: Contains the content of the document that is visible to the user.
      6. Name: <input type="text" id="name"><br>: Displays a text input field labeled “Name” where the user can enter their name.
      7. Email: <input type="email" id="email"><br>: Displays an email input field labeled “Email” where the user can enter their email address.
      8. Course: <input type="text" id="course"><br>: Displays a text input field labeled “Course” where the user can enter the course they are interested in.
      9. <input type="button" value="Set Cookie" onclick="setCookie()">: Creates a button labeled “Set Cookie” that, when clicked, calls the setCookie() function defined in the <script> tag.
      10. <input type="button" value="Get Cookie" onclick="getCookie()">: Creates a button labeled “Get Cookie” that, when clicked, calls the getCookie() function defined in the <script> tag.
      11. <script>: Starts a JavaScript block.
      12. function setCookie(): Defines a function setCookie() that is called when the “Set Cookie” button is clicked.
      13. var info="Name="+ document.getElementById("name").value+";Email="+document.getElementById("email").value+";Course="+document.getElementById("course").value;: Combines the values of the “Name,” “Email,” and “Course” input fields into a single string with the format “Name=value;Email=value;Course=value.”
      14. document.cookie=info;: Sets a cookie with the combined string containing the name-value pairs for “Name,” “Email,” and “Course.”
      15. function getCookie(): Defines a function getCookie() that is called when the “Get Cookie” button is clicked.
      16. if(document.cookie.length!=0): Checks if the length of the cookie string is not equal to 0, meaning there are cookies stored.
      17. alert(document.cookie);: Displays an alert with the contents of the cookie, which includes the name-value pairs for “Name,” “Email,” and “Course.”
      18. else: Indicates what to do if there are no cookies stored.
      19. alert("Cookie not available"): Displays an alert indicating that there are no cookies available.
      20. </script>: Closes the JavaScript block.
      21. </body>: Closes the <body> element.
      22. </html>: Closes the <html> element, indicating the end of the HTML document.

      This HTML document demonstrates how to set a cookie with multiple name-value pairs based on user input and retrieve its value using JavaScript.

      Output:

      Let’s see an example to store each name-value pair in a different cookie.

      <!DOCTYPE html>  
      <html>
      <head>
      </head>
      <body>
      Name: <input type="text" id="name"><br>
      Email: <input type="email" id="email"><br>
      Course: <input type="text" id="course"><br>
      <input type="button" value="Set Cookie" onclick="setCookie()">
      <input type="button" value="Get Cookie" onclick="getCookie()">

      <script>
      function setCookie()
      {
      document.cookie = "name=" + document.getElementById("name").value;
      document.cookie = "email=" + document.getElementById("email").value;
      document.cookie = "course=" + document.getElementById("course").value;
      }
      function getCookie()
      {
      if (document.cookie.length != 0)
      {
      alert("Name="+document.getElementById("name").value+" Email="+document.getElementById("email").value+" Course="+document.getElementById("course").value);
      }
      else
      {
      alert("Cookie not available");
      }
      }
      </script>
      </body>
      </html>

      Explanation:

      1. <!DOCTYPE html>: Declares the document type and version of HTML (HTML5 in this case).
      2. <html>: The root element of an HTML page, containing all other elements.
      3. <head>: Contains meta-information about the document, such as its title and links to external resources.
      4. </head>: Closes the <head> element.
      5. <body>: Contains the content of the document that is visible to the user.
      6. Name: <input type="text" id="name"><br>: Displays a text input field labeled “Name” where the user can enter their name.
      7. Email: <input type="email" id="email"><br>: Displays an email input field labeled “Email” where the user can enter their email address.
      8. Course: <input type="text" id="course"><br>: Displays a text input field labeled “Course” where the user can enter the course they are interested in.
      9. <input type="button" value="Set Cookie" onclick="setCookie()">: Creates a button labeled “Set Cookie” that, when clicked, calls the setCookie() function defined in the <script> tag.
      10. <input type="button" value="Get Cookie" onclick="getCookie()">: Creates a button labeled “Get Cookie” that, when clicked, calls the getCookie() function defined in the <script> tag.
      11. <script>: Starts a JavaScript block.
      12. function setCookie(): Defines a function setCookie() that is called when the “Set Cookie” button is clicked.
      13. document.cookie = "name=" + document.getElementById("name").value;: Sets a cookie named “name” with the value entered in the “Name” input field.
      14. document.cookie = "email=" + document.getElementById("email").value;: Sets a cookie named “email” with the value entered in the “Email” input field.
      15. document.cookie = "course=" + document.getElementById("course").value;: Sets a cookie named “course” with the value entered in the “Course” input field.
      16. function getCookie(): Defines a function getCookie() that is called when the “Get Cookie” button is clicked.
      17. if (document.cookie.length != 0): Checks if the length of the cookie string is not equal to 0, meaning there are cookies stored.
      18. alert("Name="+document.getElementById("name").value+" Email="+document.getElementById("email").value+" Course="+document.getElementById("course").value);: Displays an alert with the contents of the “Name,” “Email,” and “Course” cookies.
      19. else: Indicates what to do if there are no cookies stored.
      20. alert("Cookie not available");: Displays an alert indicating that there are no cookies available.
      21. </script>: Closes the JavaScript block.
      22. </body>: Closes the <body> element.
      23. </html>: Closes the <html> element, indicating the end of the HTML document.

      In conclusion, cookies are a fundamental aspect of web development, allowing developers to store and retrieve information on the client-side. In JavaScript, creating a cookie involves setting the document.cookie property with the desired name, value, and optional attributes such as expiration date (expires or max-age), path, and domain. Understanding cookie attributes is crucial for managing cookies effectively and ensuring they behave as intended. By utilizing cookies wisely, developers can enhance user experience and add valuable functionality to their web applications.

      Author

      Sona Avatar

      Written by

      One response to “JavaScript Cookies – How to Create a Cookie? – Cookie Attributes”

      1. […] Introduction: In today’s digital age, multimedia experiences play a crucial role in engaging users. Audio spectrum visualizers are a popular way to enhance the audio listening experience by providing a dynamic and visually appealing representation of the audio being played. In this tutorial, we will explore how to create an audio spectrum visualizer using HTML, CSS, and JavaScript. […]

      Leave a Reply

      Trending

      CodeMagnet

      Your Magnetic Resource, For Coding Brilliance

      Programming Languages

      Web Development

      Data Science and Visualization

      Career Section

      <script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
           crossorigin="anonymous"></script>