Home / Website Sections / Cookie Consent Banner

Cookie Consent Banner in JavaScript, Free with Live Demo

Free cookie consent banner in plain JavaScript. Accept, reject or choose categories, save the choice with a date and version, and only load analytics and ads after consent.

Open live demoDownload HTML fileView code on GitHub
Cookie Consent Banner JavaScript project: a GDPR style cookie banner with categories, saved choices and blocked scripts

Runs on: localStorage and dialog. Works in all modern browsers.

What is the Cookie Consent Banner?

A cookie banner with Accept all, Reject all and Choose buttons. The settings panel lets people switch analytics, marketing and preference cookies on or off.

The choice is saved with a date and version, and the demo shows which scripts are loaded or blocked so you can see consent working.

Good for

  • Any site with analytics or ads
  • Shops using marketing pixels
  • Sites with visitors from the EU or UK
  • Client sites that need a simple consent tool

What this project does

How it works

  1. Nothing loads before consentAnalytics and ad scripts are only added to the page when their category is switched on.
  2. Save a version and dateThe choice is stored with a version number. Change your cookie list, bump the version and everyone is asked again.
  3. Reject is one clickReject all sits next to Accept all with the same size, which is what regulators expect.

The key JavaScript

This is the heart of the project. The full file has the rest, including the screen layout and error handling.

function loadIfAllowed(src, category) {
  const c = JSON.parse(localStorage.getItem("consent-v1") || "null");
  if (!c || !c.choices[category]) return;          // blocked until consent
  const s = document.createElement("script");
  s.src = src; s.async = true; document.head.append(s);
}
localStorage.setItem("consent-v1", JSON.stringify({
  version: 2, date: new Date().toISOString(),
  choices: { necessary: true, analytics: true, marketing: false }
}));

How to use it

  1. Click Download HTML file above.
  2. Open the file in a code editor, like VS Code.
  3. Run it from a local server with npx serve . so the camera, microphone and AI features are allowed.
  4. Change the text and colors, then upload it to GitHub Pages, Netlify or your own site. It is one file with no build step.

Questions people ask

Is this enough for GDPR?

It covers the main technical parts: real choice, easy reject, no tracking before consent and a record of the choice. Check the wording with your own legal adviser.

How do I block Google Analytics until consent?

Do not put the script tag in the HTML. Call a loader function like the one shown only when analytics is allowed.

When should I ask again?

When you add new cookies, raise the version number. Many sites also ask again after 12 months.

More Website Sections projects