In this tutorial we’ll look at how to write a simple cookie consent notice using javascript that users can click to say they are happy with cookies on your site.
Getting Started
This tutorial assumes a basic knowledge of Javascript.
Note: To follow this tutorial, you will need access to a web server. This can be a localhost set up on your computer (e.g. MAMP, XAMPP etc), or an external hosting provider.
See What Specific Cookies A Site Is Using: And How You Delete Them
To view the Cookies that a site is currently running, open up the Google Chrome browser and in the developer tools (f12) go to Application > Cookies (fig.1).
To delete individual cookies, select the cookie from the ‘Name’ field, right-click your mouse and select delete.
To delete all cookies, select the domain from below the ‘Cookies’ option in the left hand column (in our example above this is http:localhost:8888), then right-click your mouse and select ‘clear’.
Creating A Cookie
To create a cookie with javascript we use ‘document.cookie’.
The following javascript will set a cookie with a name/value pairing of ‘Cookie Consent = true’. This determines whether a user has consented to cookies.
We will also add a path to the cookie which will be the root ‘/’ of the site. This prevents the message reappearing on other pages of the website after it has been dismissed.
In your javascript file we do this with:
JavaScript
document.cookie = 'CookieConsent=true; path=/;'
Adding The Cookie Expiration Date
This cookie will also need an expiration date which we will add programmatically. The expiration date in this tutorial will be 1 year after the cookie’s formation.
We add the ‘expiration’ parameter to the document.cookie as a name/value pair, separated by a semi-colon. For now the value parameter will remain empty.
JavaScript
document.cookie = 'CookieConsent=true; path=/; expiration='
Then we need to get the current date with a new Date( ) object.
JavaScript
var date = new Date()
We take this ‘Date( )’ function and chain the current ‘getTime( )’ method on to it. This method returns the number of milliseconds that have passed since the 1st Jan 1970.
To make this into an expiration date we need to add on the amount of milliseconds in the future we want the cookie to expire. For one year (365 days) in the future we would do:
365 days x 24 hours x 60 minutes x 60 seconds x 1000 milliseconds
or
365 * 24 * 60 * 60 * 1000 = 31536000000
JavaScript
var cookieData = 'CookieConsent=true; path=/; expiration='
var date = new Date()
var expirationDate = date.getTime() + 31536000000
To set the expiration date we then use the ‘setTime( )’ method, and pass in the ‘expirationDate’ variable. We add this to the original ‘cookieData’ variable and chain it to a ‘UTCString( )’ method which converts it to a string.
JavaScript
var cookieData = 'CookieConsent=true; path=/; expiration='
var date = new Date()
var expirationDate = date.getTime() + 31536000000
date.setTime(expirationDate)
cookieData += date.toUTCString()
document.cookie = cookieData
Set The Consent Cookie Via A User Consent Notice
To create the cookie we need to add some simple HTML that will include a button to be clicked to say we are happy with cookies. This HTML will have a javascript click event attached to it. This click event will also add a CSS class that we will use to remove the banner.
HTML
<div class="cookie-banner">
<p class="cookie-text">This website uses cookies to ensure you get the best experience on our website.</p>
<button class="cookie-button">Close</button>
</div>
JavaScript
var cookieButton = document.getElementsByClassName('cookie-button') [0]
cookieButton.addEventListener('click', function() {
var cookieData = 'CookieConsent=true; path=/; expiration='
var date = new Date()
expirationDate = date.getTime() + 31536000000
date.setTime(expirationDate)
cookieData += date.toUTCString()
document.cookie = cookieData
// adds a class we can use to fade out the cookie banner
cookieBanner.classList.add('cookie-fade')
})
Prevent Cookie Banner Showing On Future Visits
When the cookie consent notice has been clicked by the user to show they are happy with cookies on your site, we need to prevent the banner showing again for either the duration up to the expiration date, or until the user clears cookies from their browser history.
To do this we need to detect the cookie string ‘CookieConsent=true’ and if this is present add an HTML class to the banner which hides it from view.
To get the cookie consent string we use the split( ) method to split it at the semicolon delimiter and then filter the string to check that it begins ‘Cookie Consent’. If this is true it adds the ‘hidden’ class to hide the cookie banner.
JavaScript
if (document.cookie.split(';').filter(function(item) {
return item.trim().indexOf('CookieConsent=') == 0
}).length) {
// prevents cookie notice showing on next visit by adding a class to hide the cookie banner
cookieBanner.classList.add('hidden')
}
Final Code with all of the Elements
Note: When implementing this code, after clicking on the cookie consent banner you must refresh the web page for the cookie to show in the Google Chrome developer tools.
We will also the last piece of the CSS — an animation property and its @keyframes which causes a slight delay on the banner appearing. This stops the banner flashing up before the cookie is read by the browser.
This hasn’t been styled to any depth with CSS: the CSS used is purely functional in relation to when the banner needs to be shown or be removed, and a z-index property so it sits on top of any other elements.
HTML
<div class="cookie-banner">
<p class="cookie-text">This website uses cookies to ensure you get the best experience on our website.</p>
<button class="cookie-button">Close</button>
</div>
CSS
/* removes banner when clicked */
.cookie-banner.cookie-fade {opacity: 0; animation-fill-mode: none}
/* stops banner re-appearing */
.cookie-banner.hidden {display: none;}
/* very basic styling of the banner plus the animation properties */
.cookie-banner {
opacity: 0;
z-index: 99;
animation: initial-hide 1s ease-out 1.5s forwards;
}
/* animation keyframes that animates the banner in onload */
@keyframes initial-hide {
0% {opacity:0;}
100% {opacity:1;}
}
JavaScript
var cookieButton = document.getElementsByClassName('cookie-button') [0],
cookieBanner = document.getElementsByClassName('cookie-banner') [0]
// click even on button to add the cookie and remove the HTML banner
cookieButton.addEventListener('click', function() {
var cookieData = 'CookieConsent=true; path=/; expires='
var date = new Date()
var expirationDate = date.getTime() + 31536000000
date.setTime(expirationDate)
cookieData += date.toUTCString()
document.cookie = cookieData
// fades out cookie banner
cookieBanner.classList.add('cookie-fade')
})
// checks to see if cookie is has been set and if so keeps the banner hidden
if (document.cookie.split(';').filter(function(item) {
return item.trim().indexOf('CookieConsent=') == 0
}).length) {
// prevents cookie notice showing on next visit
cookieBanner.classList.add('hidden')
}