Friday , 17 November 2017
Home / Programming / JavaScript / Cookies – JavaScript Tutorial
Cookies
Cookies

Cookies – JavaScript Tutorial

This tutorial is part of the JavaScript tutorial series for beginners. To view the whole list of tutorials available and the order in which you should follow them, then click here.

This will be our last project in our JavaScript tutorial series. Learn how to create cookies in JavaScript. By the end of this tutorial you’ll have fully usable functions to create, grab, and delete cookies.

What are Cookies?

Cookies are pieces of information that you can store on a visitor’s computers. So, let’s say you had a first time visitor and you wanted to display a unique message to first timers. With cookies, you can check if it’s a visitor’s first time or 50th time seeing your website. You can store anything you want inside cookies. The great thing is that they’re stored on the user’s browser. So, you have no need to store it in a database or on your server.

Before we create cookies, let’s take a look at how one is formatted.

It looks confusing I know, but allow me to break it down for you. It’s all one big string, but there’s 4 parts to a cookie. Each part is separated by a semi-colon. The first part is the name of the cookie and it’s value. This can be anything you want. Your value can not have commas, semi-colons or white space. That’s important to note.  This first part is absolutely mandatory if you’re creating a cookie.

The next 3 parts are completely optional. The second part is the expiration date. The moment this time or date has passed, then your cookie is deleted. If you don’t set an expiration date, then JavaScript will delete the cookie when the user exits their browser. This date must be formatted in UTC or GMT.

The path is where the cookie can be accessed on this domain. For example, you can set this to health/tips/cardio/ and your cookie will only be accessible in directories that follow, but not any directories before it. So, if you’re on a page like health/, then you can’t use this cookie. If you don’t set any path, then JavaScript will set this to / and therefore can be accessed on any directory.

The last part is the domain. By leaving this blank, then JavaScript will set this to yoursite.com. You use this attribute when you have a subdomain. So, let’s say you create a cookie for site1.yoursite.com. Then this cookie can only be accessed on that subdomain.

All of this is put into a string. You should also know that each word shouldn’t be in capital letters. I just put it like that to make it more readable. Here’s how you would create a cookie in JavaScript.

This is how you create a cookie. We will not worry about defining a path or the domain as it isn’t really needed for our examples. However, adding these 2 pieces should be relatively easy after you’re finished this project. Hard coding a cookie isn’t the best way to do things. We’re going to create functions to help us maintain our cookies.

Setting Up The Document

Our document won’t have anything special. So get rid of any styles and update the body tag to this.

Creating A Cookie

So, let’s create a function that will create a cookie for us. Clear your script and add this bit of code.

Our function isn’t complete yet, but here’s what it does so far. First, there’s 3 parameters. The name of our cookie, the value of the cookie, and the amount of days from now the cookie will expire.

Inside our function, we create the time the cookie will expire. First, we create a variable called expiration. This variable will hold an instance of the date object. Upon it’s creation, the current date and time is stored. Since, we don’t want the cookie to expire right away, we want to add onto this. So, we use the setDate() method to help us update the current time and date. Inside this method, we use the getDate() method to grab the current day.

Don’t be fooled by the name. You’re not getting the actual date, but the day instead. Finally, we add the amount of days that were passed inside the function to the current day. This will give us the expiration date we want.

Let’s update our function to this.

We’ve added 2 new lines of code to our function. Here’s what they do. We create a variable called cookieString that will contain our huge string. To create the final string, we do numerous things. Such as, escaping the value. The escape() function makes our value portable across all networks. This is quite useful for cookies. Next, we append the semicolon to close this part and start the expires attribute.

The expires attribute value will be equal to our date object stored in expiration. However, as I stated before, the expiration date must be in UTC or GMT format. To do this, we use the toUTCString() method to do this. If you prefer GMT, then you would use the toGMTString() method. We use the UTC method because it’s universal and it’s what the developers of JavaScript recommend.

Lastly, we use the document.cookie object to store this cookie. It’s value will be our cookie name that we passed in and then our cookie string.

Now, we’re going to start grabbing cookies. Grabbing a cookie isn’t so easy because you can have multiple cookies. Since all cookies are stored in a string, we have to figure out which cookie is which and then grab the one we want.

So, we’re going to create a new function called getCookie(). Add this bit of code into your script.

We create 3 variables here. The first variable will contain the cookie we’re trying to search for. It’s basically the cookie name with an equal sign appended after it. Why do we do this? Well, let’s say we had 2 cookies named cookiefoo and cookiefoo2. Well, let’s say we were searching for cookiefoo. If we just search for the name alone, then JavaScript might end up selecting cookiefoo2. By adding the equal sign, we’re making sure we grab the right cookie.

The next variable is cookies and this variable will contain the string of cookies. Lastly, we create a variable named cookieValue which will hold the final value. We set this to null just in case we don’t end up finding our cookie.

Update your function to this.

So, we added quite a bit of code. We create a variable named start. The overall idea here is to find the 2 positions and in between those positions, will be our value. So, first, we find the starting position. We use the indexOf() method to do this. Our start variable will search the cookie string for our cookie name with the equal sign. If it finds one, it’ll return the position of that string. However, if it doesn’t, then the value will end up being -1. We don’t want to continue on if we get -1. So, we use a conditional statement to check if our value is not -1.

Inside our conditional statement, is the block of code that will continue our search if we did find the string. We reset our start variable to the position of the equal sign. This is because after our equal sign is the value of our cookie. We don’t want to grab the equal sign so we add 1 to the value to grab the beginning of our value. Next, we create a variable for the end position.

The end position will be the semi-colon after our value. So, that is what we search for next in our string. We use another condition statement to check if the end point is -1. If it is, we just set the end point to the length of the cookies string.

Lastly, we use the substring() method grabs a section of a string from one position to another. In our case, the start and end variables. We store this value into our cookieValue variable. We use the unescape() function to remove any characters we escaped. Finally, we return this value.

Phew! That’s a lot to take in, but if you take the time to look at each line, then you’ll get it!

Let”s create the deleteCookie() function. Add this bit of code into your script.

Deleting a cookie is similar to creating one. We’re actually reusing a function. The reason we do it this way instead of just accessing the setCookie() function is because we want to keep things organized. Not only that it does keep things short. JavaScript will automatically know you’re accessing the same cookie. We set it’s value to an empty string and we set it’s expire date to yesterday. Once that’s updated, your browser will delete the cookie for you.

Using our Functions

Here’s the thing, we can’t create, use, and delete cookies just by opening the HTML document. You have to use a server. Luckily, this can be any server. If you have one, then upload your files and you’re good to go. There are a lot of free ones if you don’t have one, but if you don’t feel like signing up to any, then you can just download one. I recommend USBWebserver as it really doesn’t require any installation. It’s portable, set to go, free and has everything you’ll need for this example.

Download it here – http://www.usbwebserver.net/en/

Once downloaded, unzip everything to where you want. Then, open it up and start the exe file. Next, open up the root folder and place all your files inside here. Once, that’s done, you can access your document by going to this link.

http://localhost/index.html

Easy as that! So, go to your script and add this bit of code.

First we create a cookie named foo that will expire in 3 days. Then, we output this cookie and use the getCookie() function to grab that value. Lastly, we delete it. That’s it! We now have 3 functions that will handle all the work for us.

About Cookies

Cookies should be used to store information about the user. I don’t recommend you store real sensitive information on cookies. Also know that cookies can only handle up to 4kb of data per cookie. While 1 cookie won’t do much, a lot of cookies will cause the user and server to possibly lag. You’re allowed to create as many cookies as you want. JavaScript will know when to add, update and delete cookies. With that being said, it’s safe to assume other sites can’t use your cookies. Only you can access cookies your site creates.

Conclusion

These functions are fully usable. So, I suggest you save these functions if you ever need to use them. They’re really helpful and I use them to create cookies in JavaScript. If you need more information about cookies, then go here.

https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

About Jasko Koyn

Check Also

Try-Catch Statement

Try-catch Statement – Advanced JavaScript Tutorial

The try-catch statement is a unique way to handle errors. When errors occur, usually it …

Leave a Reply

Your email address will not be published. Required fields are marked *

ULTIMATE WORDPRESS DEVELOPMENT COURSE
Want to learn how to create your own custom WordPress plugins and themes? Check out my course!
Get 93% off my course. You'll also learn how to integrate WooCommerce and BuddyPress into your projects. This is a limited time offer
Yes, I would like to get 93% off your course!
No Thanks!
close-link