I will show in this article how to create a simple cookie banner (cookie or GDPR consent) notification only with pure HTML, CSS and JavaScript, without any kind of JavaScript library which would support us in that task.
Why it is important to build on our own a simple cookie consent banner? The most important reason for that is we don’t need to add additional third-party library to our website, which will slow down it and make worse its position in search engines.
Of course you can find tens of well-working JavaScript/HTML modules cookies consent banner which will give you solution just like that. But there are many situations, that it is not possible to use external module/library, like:
- You want to learn by yourself how to do it in practice (that’s the best reason 🙂 )
- You don’t want to make a mess with tens of external modules/libraries in your project
- Your project is not allowed to contain third-party solutions – as the limitation in the sensitive project (e.g. in banking or telecommunication)
- You are maintaining the old software and you have only limited access to the source code.
So… you are in right place and here we will go step by step through whole process of creating the cookies notification bar. Let’s start 🙂
Table of Contents
Simple cookie banner (pure JS+HML+CSS)
In iframe box below you can see how will look the final solution. You can find code of cookie consent banner also on our Gitlab HERE. But let’s go through the solution step by step…
We are building the whole solution of gdpr cookie consent banner in pure HTML, CSS and JavaScript. So here we will need to have only 3 files:
- index.html – which contains whole HTML code, so the example content of the website (dummy example) + cookies consent banner.
- style.css – file with CSS styles for “Cookies consent baner”.
- main.js – JavaScript code responsible for opening and closing cookie banner and saving and reading cookie with information about user’s choice. So cookies consent banner is using a… cookie to remember user’s choice 🙂
Finally, the root directory looks like that:
HTML of simple cookie banner
Let’s move now to HTML and build the main parts of the HTML document with linked CSS and JavaScript files inside head section, and EXAMPLE CONTENT in body tag.
Example of web page – HTML code
If you would like to know more about code below, so about HTML document syntax, read THIS ARTICLE. The most important thing to mention here is that we include main.js
file in HEAD section with defer
attribute – it means that browser will download and execute external JS file after whole document has loaded.
It is useful when we have scrips which are manipulating the DOM on current page, like in our situation. So it first loads the HTML document content (DOM), next – JavaScript code which will work with that content. Sounds simple.
Check code below – it contains the example content of the page, cookies consent banner HTML code will be added in next step.
<!DOCTYPE html> <html lang="en-US"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>DEV-BAY.COM examples</title> <script type="text/javascript" src="js/main.js" defer></script> <link type="text/css" rel="stylesheet" href="css/style.css"> </head> <body> <!-- BEGIN EXAMPLE OF CONTENT --> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. </p> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae</p> <p>Pellentesque habitant morbi tristique senectus et</p> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.</p> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget.</p> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.</p> <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper.</p> <p>Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. </p> <p>Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p> <!-- CLOSE EXAMPLE OF CONTENT --> </body> </html>
Simple cookies banner – HTML
Let’s put know the HTML code of our simple cookies banner just after the <body>
tag opens.
First we have opening div with class cookies-infobar
. This is the main CSS class of that consent banner, and elements nested under that has always the same prefix: cookies-infobar
.
Why? This is a good CSS practice when we are not building our full project from the very beginning. So my assumption here is that my code will work in e.g. your project which has some already built content now.
Example – I create buttons in my cookies banner, if I would name it btn
than there is high probability that some external library (like bootstrap) have created already somewhere the same class name and my button here would get different styles than I expected. But when we use prefix with the name of the component, then we can be almost sure that all internal (nested) class names, will not conflict with classes from other attached or own sources.
<!-- BEGIN COOKIE INFO BAR --> <div class="cookies-infobar"> If you continue to use this site means you accept Terms and Conditions and Privacy Policy. We use cookies to ensure that we give you the best experience on our website. <a href="your_domain.com/terms">Read terms and conditions</a> <div class="cookies-infobar_wrapper"> <a href="#" id="cookies-infobar-close" class="cookies-infobar_btn">Accept</a> <a href="about:blank" class="cookies-infobar_btn">Reject</a> </div> </div> <!-- CLOSE COOKIE INFO BAR -->
There are in first HTML element of cookies banner some simple text of consent, in this case it is:
If you continue to use this site means you accept Terms and Conditions and Privacy Policy. We use cookies to ensure that we give you the best experience on our website.
Next we have a normal anchor (link) element which points now to “your_domain.com/terms” – so please just remember to put here in your solution the real URL of the page where user can read your official terms and conditions or privacy policy text. If you don’t want to have that, just remove this link from this code in your cookies banner.
Next we have very important part of code.
This is the container with cookies-infobar_wrapper
class. This element contains buttons:
- to accept cookies consent– this button will (in next steps) hide notification bar and save a cookie in browser to remember user’s answer for defined period of time (in this case 7 days).
- to reject cookies consent – this will move user directly to new empty page
about:blank
.
CSS styles for simple cookies banner
Let’s move now to CSS code in style.css
file. In general – CSS code here is quite basic. I have built here normal backgrounds, colors and margins like in a very basic CSS, so even with basic knowledge about CSS it should be understandable for the beginners.
.cookies-infobar { background: rgba(0, 0, 0, 0.9); color: #fff; position: fixed; width: 100%; left: 0; right: 0; bottom: 0; padding: 10px; text-align: center; } .cookies-infobar.cookies-infobar_accepted { display: none; } .cookies-infobar_wrapper { margin: 10px; } .cookies-infobar a { color: inherit; } .cookies-infobar_btn { display: inline-block; padding: 5px 10px; background: #0d9999; text-decoration: none; border-radius: 3px; color: #fff; text-transform: uppercase; font-size: 1.2em; }
Here are only 2 parts which are worth giving more explanation:
a) .cookies-infobar {...}
part of CSS code contains definition how the root element of cookies (gdpr) consent banner must be positioned on the page. So we have following definitions:
position: fixed; width: 100%; left: 0; right: 0; bottom: 0;
it means in practice – cookies banner will be fixed to the bottom of the page (even when user scrolls down, it will be fixed to the bottom of the window) and it should fill whole space from left to right of the page – width equal to 100%;
b) The following CSS definition:
.cookies-infobar.cookies-infobar_accepted { display: none; }
Is created it to hide the notification bar when user would press “Accept” button on cookies banner or if user did it earlier and script saved that information – than JavaScript code (read below) will add this class to main container.
JavaScript code of cookie banner
Let’s move now to the most interesting part – the JavaScript code. I will paste here whole code, and next we will go through that step by step:
(function () { var infoBar = document.querySelector(".cookies-infobar"); var btnAccept = document.querySelector("#cookies-infobar-close"); // Check if user has already accepted the notification if(wasAccepted()) { hideInfobar(); return; } //listen for the click event on Accept button btnAccept.addEventListener("click", function (e) { e.preventDefault(); hideInfobar(); saveAcceptInCookies(7); }); //hide cookie info bar function hideInfobar () { infoBar.className = infoBar.classList.value + " cookies-infobar_accepted"; } // Check if user has already accepted the notification function wasAccepted () { return checkCookie() === "1"; } // get cookie function checkCookie () { var name = "cookieInfoHidden="; var cookies = document.cookie.split(';'); for(var i = 0; i < cookies.length; i++) { var cookie = cookies[i]; while (cookie.charAt(0)==' ') { cookie = cookie.substring(1); } if (cookie.indexOf(name) === 0) { return cookie.substring(name.length, cookie.length); } } return ""; }; //save cookie function saveAcceptInCookies (daysOfValidity) { var now = new Date(); var time = now.getTime() + (daysOfValidity * 24 * 60 * 60 * 1000); var newTime = new Date(now.setTime(time)); newTime = newTime.toUTCString(); document.cookie = "cookieInfoHidden=1; expires=" + newTime + "; path=/"; } })();
We start the code from self invoking function and whole JavaScript code is inside it – this is important.
(function () { // whole code goes here })();
With that we are making a closure and we define the scope of our code. Like in JavaScript, the scope of some part of the code is limited to parent function. So in this case we embed everything in one scope which is running automatically when script is executed on the page, and names of our variables or functions names are available only in that scope.
If you type in console window name of the method: hideInfobar
– you will get ReferenceError
because you are not in this function scope (you are than in global scope).
With that we do not mess the global scope within window
object.
Now let’s start from the end – the helpers JavaScript functions of cookie banner:
saveAcceptInCookies (daysOfValidity)
– it saves “cookieInfoHidden” cookie in browser’s memory. It is needed because we want to save user’s acceptance and do not show again the notification in short period of time – defined here by param “daysOfValidity“. This method is triggered in line 16 on “Accept” button “click” event listener with value 7 – so it means that saved cookie will have the expiration date + 1 week, so the notification will show to the user again in next week.
checkCookie ()
– this function simply checks if “cookieInfoHidden” cookie was saved and returns its value.
Going further higher in this JavaScript code we have short functions:
hideInfobar()
– This function is just adding the “cookies-infobar_accepted” class to main element of the compoennt. As you remember from CSS part of code, there is a rule which defines that notification bar will be hidden with that class.
wasAccepted ()
– This method check the value of cookie by invoking method checkCookie ()
and comparing if value is equal to 1.
And let’s move to the top of the cookie banner js code. We are defining there in variable the “Accept” button and whole component element “.cookies-infobar” what is needed later in code.
Next we have condition which triggers function “wasAccepted()”, if true – then it hides the notification bar.
Next – important part – there is attached to Accept button element an “click” event listener which triggers a callback function. Inside that function, first we do “e.preventDefault()” what blocks execution of redirection from anchor (link) element, next it hides the notification bar, and, in the last statement:
saveAcceptInCookies(7)
it saves cookie with information that user accepted cookie (gdpr) consent, and saves this answer for 1 week in browser’s memory.
If you want to debug if cookie was saved or not, then (in Chrome browser) press F12 and go to Application tab and select in left pane “Cookies”:
Check below the final solution of simple cookie consent banner or open in here in new tab or DOWNLOAD IT HERE:
OK! This is the end!
I think that I have explained in details how to build own custom cookies (gdpr) consent banner and now you are able to reuse it in your project.