First let me explain what this JavaScript script does and then in bold I will explain my problem.
The script observes a Shopify cookie named ‘discount_code’. It starts by declaring helper functions to get and set cookies. It then attempts to fetch the ‘discount_code’ cookie and store its value. If the ‘discount_code’ cookie is present and not empty, the script displays a message with the discount code on the web page. Otherwise, it hides the message. This check is performed once at the beginning and then repeated every second. If clicked normally, the code gets copied to the user’s clipboard.
If the user clicks on the displayed discount code message while holding the alt and shift keys, the ‘discount_code’ cookie is deleted from the cookie and it is then replaced with an expired cookie. However the discount code still persists when checking out; it isn’t the cookie that still persists, so what is it? How do I clear the discount code entirely? Is this something that must be done in the liquid theme?
var codeCookieValue;
var getCookie = function(name) {
var value = "; " + document.cookie;
var parts = value.split('; ' + name + '=');
if (parts.length == 2) return parts.pop().split(";").shift();
};
var setCookie = function(name, value, expires) {
document.cookie = name + "=" + (value || "") + (expires ? "; expires=" + expires : "") + "; path=/";
};
codeCookieValue = getCookie('discount_code');
var discountMessageElement = document.getElementById('discount-message');
var copyMessageElement = document.getElementById('copy-message');
var checkCookieValue = function() {
var currentCodeCookieValue = getCookie('discount_code');
if (currentCodeCookieValue && currentCodeCookieValue !== '') {
codeCookieValue = currentCodeCookieValue;
var introMessage = "Discount Code: ";
discountMessageElement.innerHTML = introMessage+'<span class="bold">'+codeCookieValue+'</span>';
discountMessageElement.style.display = "block";
} else {
discountMessageElement.style.display = "none";
}
};
checkCookieValue(); // Run immediately
setInterval(checkCookieValue, 1000); // Then every second
// Add click event listener
discountMessageElement.addEventListener('click', function(event) {
if (!codeCookieValue) return;
if (event.altKey && event.shiftKey) {
setCookie('discount_code', '', "Thu, 01 Jan 1970 00:00:00 UTC");
checkCookieValue();
return;
}
navigator.clipboard.writeText(codeCookieValue).then(function() {
console.log('Code copied to clipboard!');
discountMessageElement.classList.add('clicked');
copyMessageElement.style.display = "block";
copyMessageElement.style.opacity = "1";
setTimeout(function() {
discountMessageElement.classList.remove('clicked');
copyMessageElement.style.opacity = "0";
setTimeout(function() { copyMessageElement.style.display = "none"; }, 3000);
}, 3000);
}).catch(function(error) {
console.error('Error copying code to clipboard: ', error);
});
});
