Create a consent message for your sites php code function

Estimated Reading Time: 2 min

Rate this post
Here’s a JavaScript code snippet to create a consent message for your website:
<!-- HTML -->
<div id="cookie-consent-banner" style="display: none; position: fixed; bottom: 0; width: 100%; background: #f8f9fa; padding: 20px; box-shadow: 0 -2px 5px rgba(0,0,0,0.1); z-index: 1000;">
  <p style="margin: 0; font-size: 14px; color: #333;">
    We use cookies to enhance your browsing experience, serve personalized content, and analyze our website traffic. By clicking "Accept All Cookies," you consent to the use of cookies. 
    <a href="/privacy-policy" style="color: #007bff; text-decoration: none;">Learn More</a>
  </p>
  <div style="margin-top: 10px; text-align: right;">
    <button id="accept-cookies" style="background: #007bff; color: #fff; border: none; padding: 10px 15px; cursor: pointer; border-radius: 5px;">Accept All Cookies</button>
    <button id="decline-cookies" style="background: #6c757d; color: #fff; border: none; padding: 10px 15px; cursor: pointer; border-radius: 5px;">Decline</button>
  </div>
</div>

<!-- JavaScript -->
<script>
  document.addEventListener("DOMContentLoaded", function () {
    const banner = document.getElementById("cookie-consent-banner");
    const acceptButton = document.getElementById("accept-cookies");
    const declineButton = document.getElementById("decline-cookies");
    
    // Check if consent has already been given
    if (!localStorage.getItem("cookieConsent")) {
      banner.style.display = "block";
    }

    acceptButton.addEventListener("click", function () {
      localStorage.setItem("cookieConsent", "accepted");
      banner.style.display = "none";
    });

    declineButton.addEventListener("click", function () {
      localStorage.setItem("cookieConsent", "declined");
      banner.style.display = "none";
    });
  });
</script>

Steps to Implement:

  1. HTML Code: Copy the HTML section and add it to your website’s footer or just before the closing <body> tag.
  2. JavaScript Code: Ensure the <script> section is included on every page.
  3. Styling: Modify the inline styles or move them to a CSS file to better match your site’s design.
  4. Policy Links: Update the href of the “Learn More” link to your site’s privacy or cookie policy.
Photo of author

Flora

Create a consent message for your sites php code function

Published

I am Flora, the publisher and founder of *Be-Smart*, a platform dedicated to sharing insights and inspiration for living a fulfilling life. With a strong background in the web, my goal is to empower people to genuinely recognize and celebrate admirable actions big or small in themselves and others.