Possums: A Tribute

A website celebrating North America's only marsupial

Javascript Tutorial: Cookies

Introduction

Cookies are used as a means for a website to store and remember data between pages. Setting a cookie is simple. There is only one required property in a cookie, the name ("name_of_cookie" below) and its value ("cookie_value" below).

document.cookie = "name_of_cookie=cookie_value";
    // Example: 
document.cookie = "name=Herbert";
document.cookie = "possum=true";

That being said, there are other properties. These include the expires property and the path property.

All cookies are session cookies by default, which means they are lost after the browser session ends. To set a permanent cookie with a longer lifespan, use the expires property.

The path property just states the URL path that the cookie belongs to. It is not required, but without it, sometimes cookies like to act up. For example, they may not want to be overwritten. Adding the path property usually fixes it. Typically "path=/" will do the trick, letting the cookie belong to the default directory.

We're fine with letting our cookies expire today, but let's include the path property. Now our cookies look like this:

document.cookie = "name=Herbert; path=/";
document.cookie = "possum=true; path=/";

Setting Up Cookies

Answer the two questions below.

What is your name?
Are you a possum?

Now, how do we make cookies for this information, so that the browser remembers it on the next page you visit? Let's make a function. (You can add this function to the submit button, or create an event listener so that it fires when the form is submitted.)

function setCookies () {
//Creates variable based on "name" input
    var userName = document.getElementById("name").value;
//Creates variable based on which radio button is checked
    var isPoss = document.querySelector("input[type=radio]:checked").value;
    
//Creates cookies using the variables above. Note the importance of quotes!
    document.cookie = "name=" + userName + "; path=/";
    document.cookie = "possum=" + isPoss + "; path=/";
}

According to your browser, your cookies say you entered this before the page reloaded:

Check this page to see if the cookies work on other parts of the website.

Getting Cookies

This is the trickier part. Cookies are stored as a string, which means to get the values we want, we have to parse the string. We're going to do that by creating an object with all our cookie properties and their values.

function getCookies () {
//The box to display the cookies
    var section = document.getElementById("cookies");
//If the browser detects cookies
    if (document.cookie) {
        var cookies = document.cookie; //Gets the cookie string
        var formValues = {}; //Creates an empty object
//let's reset the cookies variable to an array
        cookies = cookies.split(/;\s*/); //splits the string at "; " using regex notation.
//A loop for each item in the array ("name=value" and "possum=value")
        for (i = 0; i < cookies.length; i++) { 
            var prop = cookies[i].split("="); // splits array at "="
//We've created a new array with 2 values. Assign both values variables.
            var cName = prop[0]; //property name
            var cValue = prop[1]; //property value
            formValues[cName] = cValue; //sets the property/value pair in the object
        }
//Displays the values you have parsed
        section.innerHTML += "<b>Name:</b> " + formValues.name + "<br><b>Possum:</b> " + formValues.possum; 
    }
//If no cookies detected, display this message
    else {
        console.log("no cookies");
        section.innerHTML += "No cookies were found!";
    }
}//End function 

Conclusion

That's a basic guide to creating and reading cookies! This is just one common way of storing information on the web using javascript.