Display Cookie Consent Banner for EU users

How to Display Cookie Consent Banner for EU users, Free and Unlimited

by apipcc

HTML

<style>
#cookieBanner {
    background: #444;
    color: #fff;
    padding: 15px;
    font-size: 13px;
    text-align: center;
    position: fixed;
    bottom: 0;
    z-index: 1000;
    display: none; /* Hidden by default */
    justify-content: center;
    align-items: center;
}
.cookie-button {
    background: #008CBA;
    color: #fff;
    border: none;
    padding: 8px 12px;
    margin: 5px;
    cursor: pointer;
}
.cookie-button.reject {
    background: #f44336;
}
</style>

<div id="cookieBanner">
    We use cookies to personalize content and analyze traffic. <a href="/privacy-policy.html" style="color:#FFD700;">Learn more</a>.
    <button class="cookie-button" id="acceptCookies">Accept</button>
    <button class="cookie-button reject" id="rejectCookies">Reject</button>
</div>

<script>
const endpoint = 'https://apip.cc/json';

// Function to set a cookie
function setCookie(name, value, days) {
    let expires = "";
    if (days) {
        let date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}

// Function to get a cookie
function getCookie(name) {
    let nameEQ = name + "=";
    let ca = document.cookie.split(";");
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i].trim();
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

// Check if consent is already given
if (getCookie("cookieConsent") !== null) {
    document.getElementById("cookieBanner").style.display = "none";
} else {
    // Fetch user's location
    fetch(endpoint)
        .then(response => response.json())
        .then(data => {
            if (data.ContinentCode === "EU") {
                document.getElementById("cookieBanner").style.display = "flex";
            }
        })
        .catch(error => console.error("Error fetching location data:", error));
}

// Handle...