SyntaxStudy
Sign Up
jQuery Beginner 3 min read

Cookie Consent Banner

Cookie Consent

Build a GDPR-compliant cookie consent banner that remembers the user's choice in localStorage.

Example
$(function() {
  if (localStorage.getItem("cookie_consent")) return;
  const $banner = $(`<div id="cookie-banner" role="dialog" aria-live="polite" aria-label="Cookie notice">
    <p>We use cookies to improve your experience.</p>
    <button id="accept-all">Accept All</button>
    <button id="reject-all">Reject</button>
    <a href="/privacy">Learn more</a>
  </div>`).appendTo("body").slideDown(300);
  $("#accept-all").on("click", () => { localStorage.setItem("cookie_consent","all"); $banner.slideUp(200); loadAnalytics(); });
  $("#reject-all").on("click", () => { localStorage.setItem("cookie_consent","none"); $banner.slideUp(200); });
});
Pro Tip

Cookie consent banners must offer a genuine reject option — pre-checking consent or hiding reject is non-compliant.