towerops/assets/js/cookie_consent.js
Graham McIntire 3276a1cd8c
fix user session controller test
Update email input ID assertion to match actual template implementation
2026-02-03 13:42:24 -06:00

59 lines
1.7 KiB
JavaScript

/**
* Cookie Consent Handler
*
* Handles cookie consent acceptance for GDPR compliance.
* Sets a cookie that expires in 1 year when the user accepts.
*/
// Track if click listener has been added to prevent duplicates
let clickListenerAdded = false;
export function initCookieConsent() {
// Check if consent cookie already exists
if (hasConsentCookie()) {
hideBanner();
}
// Only add click listener once (on initial page load)
if (!clickListenerAdded) {
document.addEventListener('click', (event) => {
if (event.target.matches('[data-cookie-consent="accept"]') ||
event.target.closest('[data-cookie-consent="accept"]')) {
acceptCookies();
}
});
clickListenerAdded = true;
}
}
function hasConsentCookie() {
return document.cookie.split('; ').some(cookie => cookie.startsWith('cookie_consent=accepted'));
}
function hideBanner() {
const banner = document.getElementById('cookie-consent-banner');
if (banner) {
banner.style.display = 'none';
}
}
function acceptCookies() {
// Set cookie that expires in 1 year
const expiryDate = new Date();
expiryDate.setFullYear(expiryDate.getFullYear() + 1);
// Only add Secure flag in production (requires HTTPS)
const isProduction = window.location.protocol === 'https:';
const secureFlag = isProduction ? '; Secure' : '';
document.cookie = `cookie_consent=accepted; expires=${expiryDate.toUTCString()}; path=/; SameSite=Lax${secureFlag}`;
// Hide the banner with animation
const banner = document.getElementById('cookie-consent-banner');
if (banner) {
banner.classList.add('opacity-0', 'translate-y-4');
setTimeout(() => {
banner.remove();
}, 200);
}
}