Press "Enter" to skip to content

Cookies notification bar – only with HTML, CSS and pure JavaScript – step by step

I will show in this article how to create cookies (or in general: terms and conditions) notification bar only with pute HTML, CSS and JavaScript, without any kind of library which would support us here.

Of course you can find tens of well-working modules 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 external sources – when you are developer in Finances or other sensitive business
  • You are maintaining the old software and you have only limited access to 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 🙂

This is how will look the final solution. You can find this code also on our Gitlab HERE.

  • We are building everything in pure HTML, CSS and JavaScript. So here we will need to have only 3 files:
    1. index.html – which contains whole HTML code, so the example content of the website + cookies info bar.
    2. style.css – file with CSS styles for “Cookies info bar”.
    3. main.js – JavaScript code responsible for opening and closing info bar and saving and reading cookie with information about user’s choice.
  • The root directory looks in my project like:
    cookies notification bar
  • Let’s move to HTML now and build the main parts of the HTML document with linked CSS and JavaScript files inside head section, and EXAMPLE CONTENT in body tag. 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 first loads the document content, next – JavaScript code which will work over that content. Simple.
    <!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>
  • Let’s put know the HTML code of our cookies info bar just after the <body> tag opens.
    First we have opening div with class cookies-infobar . This is the main CSS class of that notification bar, 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 content now. I have creates in my cookies info bar buttons, if I would name it btn than there is high probability that you or other external library have created already somewhere the same class name and my button here would get different styles than I expected.But when we reuse on the beginning (prefix) the name of the component, then we can be almost sure that all internal, nested, class names, will not conflict with classes from other 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 element some simple text of notification, 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 wher user can read your offical terms and conditions or privacy policy text. If you do not want to have that, just remove this link from this code in your solution.

    Next we have very important part of code.
    This is the container with cookies-infobar_wrapper class. This element contains buttons:

    a) to accept the notification – 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).

    b) to reject – this will move user directly to new empty page about:blank .

  • 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 very basic CSS, so even with basic knowledge about CSS it should be understandable.
    .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 you more explanation:

    a) .cookies-infobar {...}part of CSS code contains definition how the root element of Cookies Notification Info Bar 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 – element 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 to hide the notification bar when user will press “Accept” button or if user did it earlier and script saved cookie with that information – than JavaScript code (read below) will add this class to main container.

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=/";
  }

})();

a) 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 finished 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 with window object.

b) Now let’s start from the end – the helpers functions:
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.

c) Going further higher in our 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.

d) And let’s move to the top of the script. We are defining there in variable the “Accept” button and whole component element “.cookies-infobar” what is needed later in code.

Next we have coditin 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 notification, 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”:

cookies notification bar
cookies notification bar

Check below the final solution 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 whole solution’s code works and now you are able to reuse it in your project.