Cookie consent banner with stored choice
A bottom cookie banner that stores the visitor's choice, loads optional scripts only after opt-in and can be reopened from the footer.
Tailwind CSSModalscookiesconsentprivacybanner
Live preview
Code
How it works
What it solves
Privacy rules in many regions require that optional cookies and trackers load only after a visitor agrees, and that withdrawing consent is as easy as giving it. This pattern handles the common case with a small, dependency free script.
How it works
The banner is a non-modal dialog element role fixed to the bottom, hidden by default so there is no flash for returning visitors. On load the script reads a JSON record from localStorage, wrapped in try/catch because storage can throw in private windows. If a choice exists, it is applied right away; otherwise the banner is shown.
The three buttons are handled by one delegated listener that reads data-consent. Accept, reject and save all call the same save function, which writes the record with a timestamp, hides the banner and runs apply. Optional code, here an analytics script, is injected only inside apply when the flag is true, so nothing loads before agreement.
Adapting it
- Add more categories by adding checkboxes and keys in the saved object.
- Change the storage key suffix to force a fresh prompt after a policy update.
- Provide a footer button with
data-reopen-consentso people can change their mind.
Pitfalls
- Reject must be as prominent as accept; do not hide it in a link.
- Store the choice on the server too if you must prove consent later.
- Scripts already present in the HTML will run regardless, so keep them out of the page source.
How to use it
- Include the banner markup near the end of your layout and the script after it.
- Replace the analytics script path in
applywith your own optional loader. - Add a footer button that carries the
data-reopen-consentattribute. - Keep strictly necessary cookies out of the consent logic.
Licence: DEV3 Snippet Licence. Free to use, change and ship in personal and commercial projects. Attribution is appreciated, not required. Please do not redistribute snippets as a collection.