Files
sodino/public/js/banner-frontend.js

107 lines
3.7 KiB
JavaScript

(function () {
const clicked = new Set();
function getCookie(name) {
const value = '; ' + document.cookie;
const parts = value.split('; ' + name + '=');
if (parts.length === 2) {
return parts.pop().split(';').shift();
}
return null;
}
function hideBanner(banner) {
if (!banner) {
return;
}
banner.style.display = 'none';
banner.setAttribute('aria-hidden', 'true');
const bannerId = banner.dataset.bannerId;
if (bannerId) {
const backdrop = document.querySelector('.sodino-banner-backdrop[data-banner-backdrop="' + bannerId + '"]');
if (backdrop) {
backdrop.style.display = 'none';
}
document.cookie = 'sodino_banner_' + bannerId + '=hidden; path=/; max-age=' + 60 * 60 * 24;
}
}
function sendClick(bannerId) {
if (!bannerId || clicked.has(bannerId) || !window.sodinoBannerFrontend) {
return;
}
clicked.add(bannerId);
fetch(window.sodinoBannerFrontend.ajaxUrl, {
method: 'POST',
credentials: 'same-origin',
keepalive: true,
headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
body: 'action=sodino_banner_click&banner_id=' + encodeURIComponent(bannerId) + '&nonce=' + encodeURIComponent(window.sodinoBannerFrontend.nonce),
}).catch(function () {});
}
document.addEventListener('click', function (event) {
const closeButton = event.target.closest('.sodino-banner-close');
if (closeButton) {
event.preventDefault();
event.stopPropagation();
hideBanner(closeButton.closest('.sodino-banner-wrap'));
return;
}
const backdrop = event.target.closest('.sodino-banner-backdrop');
if (backdrop) {
event.preventDefault();
const banner = document.querySelector('.sodino-banner-wrap[data-banner-id="' + backdrop.dataset.bannerBackdrop + '"]');
hideBanner(banner);
return;
}
const target = event.target.closest('.sodino-banner-link');
if (target) {
sendClick(target.dataset.bannerId);
}
});
document.addEventListener('keydown', function (event) {
if (event.key !== 'Escape') {
return;
}
const popup = document.querySelector('.sodino-banner-popup:not([aria-hidden="true"])');
if (popup) {
hideBanner(popup);
}
});
document.querySelectorAll('.sodino-banner-wrap').forEach(function (banner) {
const bannerId = banner.dataset.bannerId;
if (getCookie('sodino_banner_' + bannerId) === 'hidden') {
banner.style.display = 'none';
banner.setAttribute('aria-hidden', 'true');
const backdrop = document.querySelector('.sodino-banner-backdrop[data-banner-backdrop="' + bannerId + '"]');
if (backdrop) {
backdrop.style.display = 'none';
}
return;
}
if (banner.classList.contains('sodino-banner-popup')) {
setTimeout(function () {
if (getCookie('sodino_banner_' + bannerId) !== 'hidden') {
const backdrop = document.querySelector('.sodino-banner-backdrop[data-banner-backdrop="' + bannerId + '"]');
if (backdrop) {
backdrop.style.display = 'block';
}
banner.style.display = 'block';
banner.setAttribute('aria-hidden', 'false');
}
}, 900);
}
});
})();