function dimButtonsIfVariantUnavailableOrSold() {
var productVariants = document.querySelector(".product-variants");
var buttons = Array.from(document.querySelectorAll(".c-swatches__button"));
if (!productVariants || !buttons.length) return;
// Function to check if the current variant is in stock
function isVariantInStock() {
// Returns true if data-variant-in-stock="true"
return productVariants.getAttribute("data-variant-in-stock") === "true";
}
// Function to handle each button's availability state
function buttonsHandler(button) {
button.classList.remove("is-unavailable");
// If the current variant is out of stock and the button is active, mark it as unavailable
if (!isVariantInStock() && button.classList.contains("is-active")) {
button.classList.add("is-unavailable");
}
}
// Special handling for single swatch scenario
function handleSingleSwatch() {
if (buttons.length === 1) {
var singleButton = buttons[0];
if (isVariantInStock()) {
singleButton.classList.remove("is-unavailable");
singleButton.style.opacity = "1"; // Ensure full visibility
singleButton.style.pointerEvents = "auto"; // Ensure it is interactable
} else {
singleButton.classList.add("is-unavailable");
}
}
}
// Add click event listeners for buttons
buttons.forEach(function (button) {
button.addEventListener("click", function () {
buttons.forEach(buttonsHandler); // Update all buttons on click
handleSingleSwatch(); // Check the single swatch condition again
});
});
// Initial handling of single swatch scenario
handleSingleSwatch();
}
// Initialize the logic on page load and Mercury reloads
document.addEventListener("DOMContentLoaded", dimButtonsIfVariantUnavailableOrSold);
window.addEventListener("mercury:load", dimButtonsIfVariantUnavailableOrSold);