Set, Increment and Remove Cookies using Cookie JS

Posted on September 5, 2017 by Dan Doicaru in jQuery/JavaScript Category with Medium Difficulty

In this tutorial you will learn how to set or remove a cookie, get or increment a cookie value and set an expiration date in days using a simple cookie JS plugin. Read below to find out how you'll do it!

Basically, we will do a simple page views counter using cookies. Whenever a user refreshes the page, our cookie value should increment by one. Then we can write a condition to do whatever you want when the maximum value is reached.

Notes for Testers

As a quick first note, before starting the tutorial, remember that JavaScript cookies does NOT work on your local pages. You must have a domain and a server where to upload your content if you want to test it inside any page.

Video Tutorial

Loading the Cookie JS Plugin

While I mostly hate using external plugins because of the loading performance, they are always handy when it comes to code something fast.

Before starting the project, you will need to include the JavaScript cookie plugin in your page footer. There are also available some unofficial CDN hosted files if you plan to do some tests.

<script src="/path/to/js.cookie.js"></script>

Set, Read and Remove Cookies using JS Cookie Plugin

To set a cookies with this plugin is pretty easy, just by using the Cookie.set() function. You can find more details about basic usage on the official documentaion.

Cookies.set('name', 'value');

To set or create a cookie that expires 7 days (1 week) from now, which is valid on any page in your domain or site.

Cookies.set('name', 'value', { expires: 7 });

To read or get a cookie value we will use the Cookie.get() function from our cookie JS plugin.

Cookies.get('name');

To delete or remove a cookie, you can use the Cookie.remove() function.

Cookies.remove('name');

Increment Cookie Value with Plain JavaScript

If you have a number for your cookie value, you can increment or increase that number by one, two or how much you need, at every refresh of the page.

Keep in mind that your cookie will be stored globally, in all pages of your site. You can also run the script only on a specified page, to increment the value, but the cookie will be still available in any page of your domain.

Initializing Variables

We will need a total of 5 variables to initialize when the page loads:

  • one variable to know how many hits/views you want to store on your domain (max value)
  • one to set the cookie value by default to 1
  • another one to store the number for the expiration days, 7 in this my case
  • one with the cookie name, to not repeat the same text again (keep the code clean)
  • and the last one to get the initial value of our cookie when the page loads
// Cookie Settings
var maxCookieValue = 10, initCookie = 1, expirationDays = 7;
var cookieName = "myCookie";
var getCookie = Cookies.get(cookieName);

Checking if Cookie Exists

First of everything we will need to check if our cookie js exists. If the cookie is not set or does not exists, you can create it from scratch.

if (getCookie == null) {
	// set the cookie
} else {
	// get the cookie, increment it and check for max value
}

Remember that we used some variables above. If the cookie variable has no value (is null) or is expired, we will set the cookie with the value 1, which is the initCookie variable.

Cookies.set(cookieName, initCookie, { expires: expirationDays });

Get, Increment and Set Cookie JS

Before increasing the value by one, we must check if our cookie value is between the minimum and maximum range, in our case 1 (the minimum value) and 10 (the maximum value) and to prevent the script to increment the value after the maximum number is reached.

if (getCookie >= initCookie && getCookie < maxCookieValue) {
	getCookie++;
	Cookies.set(cookieName, getCookie, { expires: expirationDays });
}

Increase and Set Cookie JS in Chrome Console

You can also create another conditional to check if the current cookie is the same as the maximum value.

if (getCookie >= maxCookieValue) {
	// if cookie is equal with the number you've set, then do something
	// hide or show an element, delete the cookie etc...
}

Check Cookie JS for Max Value

If you want to test further after cookie reached the limit, you can either delete your cookies or write the Cookies.remove() function in the if statement above.

Cookies.remove(cookieName);

Adding the Complete Code

To understand the code easier, I've added the console.log() function to output the results in your browser's console. You can remove them after debugging. Check the full code below:

// Cookie Settings
var maxCookieValue = 10, initCookie = 1, expirationDays = 7;
var cookieName = "myCookie";
var getCookie = Cookies.get(cookieName);

// Under the Hood
if (getCookie == null) {
	Cookies.set(cookieName, initCookie, { expires: expirationDays });
	console.log('Cookie set to value 1');
} else {
	if (getCookie >= initCookie && getCookie < maxCookieValue) {
		getCookie++;
		Cookies.set(cookieName, getCookie, { expires: expirationDays });
		console.log('Cookie incremented. Value is ' + getCookie);
	}
	if (getCookie >= maxCookieValue) {
		console.log('Cookie max allowed value reached: ' + getCookie);
		// if cookie is equal with the number you've set, then do something
		// hide an element, delete the cookie etc...
	}
}

Have in mind that cookies can be deleted by users or automatically when the browser is closed (in private/incognito mode). You can download the files below and check the live demo.

Live Demo

Download

Related Articles
Comments
Hint: Wrap your code syntax (html, css or others) between <pre> and </pre> tags. All comments are moderated.


+ 4 = 8

Search
Subscribe by E-mail

HTML-TUTS is created and maintained by Dan Doicaru.
This website is a rebrand to Extreme Design Studio (extremestudio.ro), built under WordPress platform.