← Back to the demo

Documentation

Consent is one JavaScript file and one stylesheet. It shows a cookie banner, records the visitor's choice in localStorage, and keeps scripts you mark as gated from running until their category is allowed. No dependencies, no build step, no network requests.

What this is. Consent records a choice and withholds scripts until that choice exists. That is all it does. It does not scan your site for cookies, it does not send anything to a server, it does not keep an audit trail of who agreed to what, and it does not decide what your site is legally required to show. Those parts are yours, and a lawyer's if you need one.

Install

Copy consent.js and consent.css into your project and include them once per page. Create the instance as early as you can, ideally in the <head> or at the top of <body>, so the banner appears before gated scripts are reached.

<link rel="stylesheet" href="consent.css">
<script src="consent.js"></script>
<script>
  var consent = new Consent({
    privacyUrl: '/privacy'
  });
</script>

With no stored decision the banner opens on load. Once the visitor decides, the answer is stored with a version and a timestamp, and the banner stays closed until the record is older than expiryDays or the version changes.

Gating scripts

Any script tag with type="text/plain" and a data-consent attribute is held back. When the matching category is allowed, Consent copies the tag into a fresh script element and the browser runs it.

Inline script:

<script type="text/plain" data-consent="analytics">
  window.dataLayer = window.dataLayer || [];
  // your analytics snippet
</script>

External file. Use data-src instead of src so the browser does not fetch it before consent:

<script type="text/plain" data-consent="marketing" data-src="/pixel.js"></script>

All other attributes on the tag are copied across, so async, defer, id and data attributes survive. A gated script that has run is marked with data-consent-activated and is not run a second time.

Gating is applied when the instance is created and again after every save. A script that already ran stays run: withdrawing consent stops future scripts from starting, it cannot unload code the browser has already executed. If you need a clean state after a withdrawal, reload the page.

Options

OptionTypeDefault
storageKeystring'consent' — the localStorage key.
versionstring'1' — bump it when your categories change and every visitor is asked again.
expiryDaysnumber180 — days before the stored answer is ignored and the banner shows again.
positionstring'bottom', 'bottom-left' or 'center'.
titlestringBanner heading.
descriptionstringBanner body text.
acceptLabelstring'Accept all'
rejectLabelstring'Reject all'
saveLabelstring'Save choices'
settingsLabelstring'Preferences'
privacyLabelstring'Privacy policy'
privacyUrlstringEmpty. When set, the label becomes a link.
categoriesarraySee below.
autoShowbooleantrue — open on load when there is no valid record.
allowDismissbooleanfalse — when true, clicking the backdrop of a centre dialog closes it without saving.
onInitfunctionCalled with the current state after setup.
onChangefunctionCalled with the new state after every save.

Categories

Each category is an object with id, label, description and an optional required flag. Required categories are always stored as allowed and their checkbox is disabled. The default set is necessary (required), analytics and marketing.

new Consent({
  categories: [
    { id: 'necessary', label: 'Necessary', description: 'Required for the site to work.', required: true },
    { id: 'analytics', label: 'Analytics', description: 'Page views and which pages get used.' },
    { id: 'marketing', label: 'Marketing', description: 'Campaign pixels and retargeting.' }
  ]
});

The id is what you put in data-consent on a script tag, so the two must match exactly.

API

MethodReturnsWhat it does
get()object{ decided, categories, timestamp, version }. Before a decision, decided is false and categories is empty.
allows(id)booleanWhether one category is allowed.
valid()booleanWhether a usable record exists for the current version and expiry.
set(map)stateSave a set of categories, for example { analytics: true, marketing: false }. Required categories are forced on. Closes the banner and applies gating.
acceptAll()stateAllow every category.
rejectAll()stateAllow only the required categories.
reset()instanceDelete the stored record and fire consent:change. The banner does not open by itself.
open()instanceShow the banner. Safe to call twice.
close()instanceHide the banner without saving.
destroy()instanceRemove the banner, event listeners and focus trap. The stored record is left alone.

Consent.defaults holds the default options and Consent.version is the script version.

Events

Every save and every reset fires a consent:change event on document. The new state is in event.detail.

document.addEventListener('consent:change', function (event) {
  if (event.detail.categories.analytics) {
    startAnalytics();
  }
});

Use this for scripts you would rather load yourself, instead of the data-consent tags.

Reopening the banner

Add data-consent-open to any element, usually a footer link, and clicking it opens the banner so a visitor can change their mind.

<a href="#" data-consent-open>Cookie settings</a>

Styling

The markup uses plain class names so you can restyle it without fighting specificity: .consent, .consent__title, .consent__desc, .consent__actions, .consent__btn, .consent__btn--primary, .consent__btn--ghost, .consent__prefs, .consent__cat, .consent__cat-label, .consent__cat-desc and .consent__link. The position variants add consent--bottom, consent--bottom-left or consent--center on the root element.

consent.css uses CSS custom properties for colours and spacing, so a theme is usually a handful of variable overrides rather than new rules.

Accessibility

The banner is a role="dialog" with aria-modal, labelled by its title and described by its body text. Tab and Shift+Tab stay inside the banner while it is open, Escape closes it when allowDismiss is on or when a decision already exists, and focus returns to the element that opened it. The preferences panel is a set of native checkboxes, and the required category is a disabled checkbox so it reads correctly to a screen reader.

Browser support

Current versions of Chrome, Edge, Firefox and Safari, desktop and mobile. Consent uses localStorage, CustomEvent and plain DOM APIs. In a browser with storage blocked the banner still works for the session, it just cannot remember the answer.

Files

FileWhat it is
consent.jsThe plugin. Unminified, commented, no dependencies.
consent.cssBanner styles and position variants.
index.html, demo.cssThe demo page and its styles. Not needed on your site.
docs/index.htmlThis documentation.

External costs

None. Consent runs in the browser with no server, no account, no API key and no third-party service. There is nothing to sign up for and nothing that bills per request or per visitor.

Support

Questions, bug reports and feature requests: use the support tab on the item page. Include the browser, the options you pass and, if you can, a link to a page that shows the problem.