Reputation: 1
I'm a first time Squarespace user trying to inject JavaScript into my website so that I can customize the checkout button to redirect customers to a quote form instead of the regular checkout. I'm having trouble getting it to actually work. When I click on the button there are no errors in the console. The result is still a direction to the default checkout page after it redirects to the correct form for half of a second. The button seems to be dynamic. At first, I wasn't able to correctly target the button, but now the console prints the correct actions to recognize the button being clicked.
document.addEventListener("DOMContentLoaded", function() {
function checkout(event) {
event.preventDefault(); // Prevent default behavior
console.log('Checkout button clicked.'); // Log that the button was clicked
window.location.href = '/quoteform'; // Redirect to checkout form
}
// Function to initialize checkout button and event listener
function initializeCheckoutButton() {
const checkoutButton = document.querySelector('.WPMtsTeKIf6hjb69ukR9.cart-checkout button, .d_v7cGDEhQylt5v3Moan.sqs-editable-button.sqs-button-element--primary.cart-checkout-button');
if (checkoutButton) {
checkoutButton.addEventListener('click', checkout);
console.log('Checkout button found and event listener attached.');
} else {
console.error('Checkout button not found.');
}
// Debugging output
console.log('Checkout button:', checkoutButton);
}
// Delay initialization until all elements are fully loaded
window.addEventListener('load', function() {
// Initialize checkout button after load
initializeCheckoutButton();
// MutationObserver to detect when the checkout button is added to the DOM
const observer = new MutationObserver(function(mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
// Check if any of the added nodes match the checkout button selector
const checkoutButton = mutation.target.querySelector('.WPMtsTeKIf6hjb69ukR9.cart-checkout button, .d_v7cGDEhQylt5v3Moan.sqs-editable-button.sqs-button-element--primary.cart-checkout-button');
if (checkoutButton) {
checkoutButton.addEventListener('click', checkout);
console.log('Checkout button found and event listener attached (dynamic).');
}
}
}
});
// Start observing changes
observer.observe(document.body, { childList: true, subtree: true });
});
});
I've used the following code. Is there a reason why this is forcing a redirect to the default page or have any other script suggestions to prevent this?
Upvotes: 0
Views: 53