Cookie consent plugins are plentiful, a quick google search and you’ll find some JavaScript to pull in via a CDN, a node package to install or a random third party plugin for the platform you’re working within. However I sometimes get rather frustrated when I use an off the shelf solution and attempt to bend it to fit my requirements; for example overriding the awful overly specific CSS that commonly ships with it, or when I want to bundle it with my project build rather than link via a CDN.

Recently I needed a cookie consent pop up in the style of a modal, so I thought rather than scouring the web for an hour for something that almost does what I need it to do, then have to hack away for another hour customising it, I wondered how hard would it be to roll my own; turns out that there really isn’t an awful lot to it!

The whole thing has to, quite ironically, depend on a cookie being set to remember the user’s consent, so to start with we need to implement methods to handle the getting and setting of cookies via JavaScript. This has unsurprisingly been done time and time again and posted all over the web, there’s no need to reinvent the wheel here, for these two methods I’ve simply used the examples documented on

As for the rest of the code, we would need to:

  • Define a unique cookie namespace
  • Define a time period until the cookie expires
  • Hook up the click event on the “Accept” button to set the cookie
  • Implement a method to check for the existence of a cookie, to then qualify if the cookie popup modal should be fired when the user revisits the site or a new page is loaded

Cookie consent modal JavaScript

The majority of the Javascript is written in ES5, however since we are using the Bootstrap modal plugin, which has a jQuery dependancy, I am handling the event listeners with jQuery also.

Modal popup HTML

The popup itself can be dismissed without clicking accept, however it will persist as the user browses other pages on the site until the user accepts. It should be noted that the following example is merely indicative to demonstrate functionality for the purpose of this tutorial, and is not necessarily GDPR compliant.

And there you go, a nice and clean un-bloated solution which can be extended to fit your needs.



Notify of
Sort by:   newest | oldest | most voted
Thomas F.
Thomas F.

Thank you! This was helpfull – saved me a few hours.

3 months 1 day ago

Hello, I’m not a javascript professional and don’t understand how to change the script the modal will be shown only once or maybe after 7 days.

What does it mean “Should the cookie popup be shown?” because when modal opens on site load?

6 months 17 days ago