Codementor Events

How To Build a Simple Cookie Banner in 10 Lines of HTML/Js

Published Jul 26, 2022
How To Build a Simple Cookie Banner in 10 Lines of HTML/Js

With GPDR regulations coming in force in certain countries, it is good to inform visitors about our data treatment policy. But, the search for a nice plugin or tool to integrate is often a long one. In this post we are going to build a robust cookie banner in as few lines as possible.

For a simple site, a nice cookie banner should be one that is simple to integrate and remembers the choices users made and acts accordingly. Local storage is the perfect choice for storing persistent information in the browser.

There are two approches possible: the all-or-nothing approach or the customised approach. The all-or-nothing approach informs the user that, to contibue browsing the site, they must accept all conditions. The customised approach means to give the user the choice to select what components they wish or not to enable. Though both works, the first one is simple to build and integrate while the second offers a nicer usage experience for site visitors. We'll go for the first approach in this post.

It's what codementor uses.

codementor.png

What Is localStorage?

JavaScript has the localStorage API to store data in a key value format in the browser that persists across sessions. The data is already namespaced by domain name. This is to ensure that keys across sites do not mix together. You can inspect localStorage records typically under the Application label.

mozilla.png

To set the keys, call setItem method.

localStorage.setItem('preferredColor', 'teal');

To retrieve keys, use the getItem method.

localStorage.getItem('preferredColor', 'teal');

Since it is an object, accessing the value directly also works.

localStorage['preferredColor'];

It is advisable to store all values as strings.

Building the Banner

We'll add a text-only banner informing the user of the implications of visiting the site. We'll also add a button, well, [ a link to click on ], with an id of consent-button.

<div id="gdpr-thing">
  By using this website, you consent to privacy policies mentionned on <a href="#">this page</a> [ <a id="consent-button" href="#">Ok</a> ]
</div>

Then we wait for the page to load

window.addEventListener('load', (event) => {

});

Then, if the button is clicked, hide the banner.

window.addEventListener('load', (event) => {
      document.getElementById("consent-button").onclick = function() {
        document.getElementById("gdpr-thing").style.display='none';
      };
});

We need to also set a value to remember that the user accepted the policy.

// ...
      document.getElementById("consent-button").onclick = function() {
        document.getElementById("gdpr-thing").style.display='none';
        localStorage.setItem('gdpr-accept', 'ok'); // <- this
      };
// ...

Then, on page load, we check if the user accepted the clause before and if so, hide the banner

window.addEventListener('load', (event) => {
        if (localStorage.getItem('gdpr-accept')==='ok'){
            document.getElementById("gdpr-thing").style.display='none';
        }

      // if button click code
});

And, that's all!

Here's the full code:


<div id="gdpr-thing">
  By using this website, you consent to privacy policies mentionned on <a href="#">this page</a> [ <a id="consent-button" href="#">Ok</a> ]
</div>
<script type="text/javascript">
  // On page load
    window.addEventListener('load', (event) => {
        // Check if already accepted before, hide banner
        if (localStorage.getItem('gdpr-accept')==='ok'){
            document.getElementById("gdpr-thing").style.display='none';
        }
    
      // If accept, hide banner and remeber choice
      document.getElementById("consent-button").onclick = function() {
        document.getElementById("gdpr-thing").style.display='none';
        localStorage.setItem('gdpr-accept', 'ok');
      };
    });
</script>

Wrapping Up

If you build an advanced version of it, feel free to link the codepen in the comment section below. Hope you enjoed the article!

You can view the banner live here

Discover and read more posts from Abdur-Rahmaan Janhangeer
get started
post commentsBe the first to share your opinion
Show more replies