Skip to Content
Vanilla JS Project: Make a Cookie Banner

Vanilla JS Project: Make a Cookie Banner

Hey CodeNewbies and welcome! If you’re here it’s because you’re looking for a project to practice your Javascript skills. Well you’ve come to the right place! This Vanilla JS project to make a cookie banner will help you practice manipulating the DOM (Document Object Model), as well as thinking like a developer. Includes cookie banner Codepen example!

Estimated reading time: 6 minutes

There are three problems in this post that we’re going to solve:

Feel free to stick with just the first part of this project if you’d like a simple project.

a cookie banner sits at the top of a web page above the header area

cookie banner with green button sits above the page header area
Yield: Manipulate DOM

Cookie Consent Banner with Vanilla JS

Prep Time: 5 minutes
Active Time: 20 minutes
Additional Time: 10 minutes
Total Time: 35 minutes
Difficulty: Code Newbie

Create and manipulate DOM elements in this easy to get started, real world tutorial.

Instructions

  1. Paste this HTML in the HTML section of your Pen & Paste this CSS in the CSS section of your Pen.

    Your pen should look a bit like a web page:

    screenshot of the codepen project which has a header, body and footer that resemble a web page
  2. Create a div element in the JS section of your Pen by using the createElement() method.
  3. Add a class name and insert text and a button into the Cookie Consent Banner using classList.add() and innerHTML methods. You can use this HTML for your innerHTML content if you'd like.
    screenshot showing how classList add and inner HTML were used to manipulate the DOM element
  4. Insert this DOM element you've created into the DOM using prepend()
    the div element created has been added into the DOM. The cookie banner is currently unstyled
  5. Style the Cookie Banner. You can use this CSS, or design it yourself.
    the cookie banner and button are now styled
  6. Remove the Cookie Banner when the user clicks the button. Use querySelector to select the button by its class and store it in a variable. Add an event listener for the click event to the button variable you created. Use the remove() method to remove the banner element from the DOM.
  7. OPTIONAL: Add a setTimeout() function within the event handler to prepare for the next steps.
    the remove method is wrapped in a set timeout function for 1000 miliseconds

Did you make your own Cookie Banner?

Share yours on social and link this article for your friends!

Create Feedback for the user with Vanilla Javascript

the cookie banner button text now says bye bye and the button almost appears like it's pressed downwards

To build a user friendly interface for the cookie banner, we need to tell the user something happened when they clicked the button.

How to upgrade the usability of the cookie banner:

We can use setAttribute() on the aria-pressed attribute to tell non or low vision users that the button has been pressed. Inside of the event listener, use the setAttribute function to grab the aria-pressed attribute and change its value to true.

the set attribute function is called on the button to change the aria-pressed attribute from false to true

We can use Vanilla JS to add a class name to the button called 'clicked':

the class list add methods are called on the button to add a class called "clicked" to the button.

Along with this Javascript added class, we can use CSS to change the look of the button when it is clicked on for visual users:

border and outline styles are added to the clicked class to make the button change when it's been clicked on

Finally, we can also use textContent to update the button text.

code inside the event listener shows how textContent is called on the button element and the words "bye bye" are inserted to replace the original "Got It" button text

Check out how to create accessible toggle buttons with ReactJS here!

Prevent CLS using CSS positioning:

Currently, the banner is being prepended to the body tag of the document. That is placing it above the header area. When we click the button and remove the banner, the entire web page shifts up ⬆️ to replace this now blank space.

What is CLS and why do we have to prevent it?

As a developer the core metric which decides whether your project passes ✅ or fails ❌ is usability. In industry terms it’s called UX (for User Experience).

Google has created several metrics to programmatically calculate the success or failure of your user’s experience when using your web applications. Those metrics are called Core Web Vitals.

One of those metrics is called CLS which stands for Cumulative Layout Shift. It’s a metric that measures how much elements move around as the user is interacting with your web page. A great example of this is when you are navigating a website on your phone and go to click a link but in the second it takes your thumb to hit the screen the link shifts down and another link is where your thumb now is. (OMG I HATE THAT!) As a developer, it’s important to prevent frustrating experiences for your users as much as possible.

Check out how to pass LCP (another tricky web vital) without a developer.

How do we prevent the banner from shifting our content?

We want to position the cookie banner on top of the document body instead of inside of it. To do that, we need to add fixed positioning to the banner, and add a top and z-index style as well.

The fixed position of this element will set the banner as relative to the window which will give us more control if other elements in our document have positioning set on them. It also prevents cumulative layout shift because we have no other elements that it could shift around.

  position: fixed;

The top style will ensure that there is absolutely no space between the banner and the top of the window.

  top: 0;

And finally, the z-index style ensures that the banner sits at the very top of the stack, which will prevent other elements from overlapping it.

  z-index: 2; 

See the completed banner on CodePen here:

By now you’ve learned how to create a DOM element, add a class and HTML inside of it, insert the element into the DOM, and remove it from the DOM with an event listener. All with just Vanilla Javascript!

If you’re reading this, you also created user feedback using CSS + classList.add(), using setAttribute(), and using textContent.

Finally, you have figured out how to solve for a tricky Core Web Vital called CLS (Cumulative Layout Shift).

Materials

HTML – Step 1

<header>
  <div>Site Title</div>
  <nav>
    <ul>
      <li>Home</li>
      <li>About</li>
      <li>Contact</li>
    </ul>
  </nav>
  </header>
  <main>
  </main>
  <footer>
      <nav>
    <ul>
      <li>Home</li>
      <li>About</li>
      <li>Contact</li>
    </ul>
  </nav>
  </footer>

CSS – Step 2

/**
Web Page Styles
**/
* {
  font-family: "Arial", sans-serif;
  font-size: 16px;
}
header {
  background: white;
  color: darkblue;
  border-bottom: .5px solid darkblue;
  width: 100%;
  padding: 2%;
  display: grid;
  grid-template-rows: 1fr;
  grid-template-columns: 1fr 1fr;
}
header div {
  grid-column: 1 /span 1;
  grid-row: 1;
  display: flex;
  margin: 1em;
  justify-self: left;
}
nav {
  grid-column: 2 /span 1;
  grid-row: 1;
  display: flex;
  justify-content: flex-end;
}
nav ul {
  display: flex;
  justify-content: space-evenly;
  width: 40%;
}
nav li {
  list-style: none;
}
main {
  min-height: 600px;
  background: url('https://images.unsplash.com/photo-1651505343248-26d2400939c4?crop=entropy&cs=tinysrgb&fm=jpg&ixid=MnwzMjM4NDZ8MHwxfHJhbmRvbXx8fHx8fHx8fDE2NTM5NjcxMTM&ixlib=rb-1.2.1&q=80') 0 0 no-repeat;
  opacity: .5;
}

Inner HTML – Step 3

This site uses 🍪 cookies 🍪 to track everything you do, except not really, idk actually I am just an example <button class="btn" aria-pressed="false">Got It</button>
.cookie-message {
  width:100%;
  padding: 2% 0;
  background: white;
  box-shadow: 12px 12px 25px #444444aa;
  border-bottom: .5px solid limegreen;
  text-align: center;
  letter-spacing: .12em;
}
.btn {
  width: 100px;
  margin-left: 1%;
  background-color: limegreen;
  padding: .5% 1%;
  border: 2px inset white;
  outline: 2px outset black;
  color: white;
  border-radius: 5%;
}
Skip to Instructions