Skip to content

Instantly share code, notes, and snippets.

@molinto
Last active October 21, 2020 15:00
Show Gist options
  • Save molinto/d506818d6a5c4185bc5d078828c40ae4 to your computer and use it in GitHub Desktop.
Save molinto/d506818d6a5c4185bc5d078828c40ae4 to your computer and use it in GitHub Desktop.
Squarespace to Klaviyo - View Product & Add to Cart events (with variants)
// I'M USING THE 'BRINE' THEME & GBP CURRENCY
// REMEMBER TO PLACE THE FOLLOWING IN THE HEADER (https://x.squarespace.com/config/settings/advanced/code-injection)
/////////////////////////////////////////////////////////////////////////////////////
<script type="application/javascript" async src="https://static.klaviyo.com/onsite/js/klaviyo.js?company_id=PUBLIC_API_KEY_HERE"></script>
<script>var _learnq = _learnq || [];</script>
// FOLLOWING PART IS PLACED IN A <CODE> BLOCK IN THE ADDITIONAL-INFO SECTION ON PRODUCT EDIT PAGE
///////////////////////////////////////////////////////////////////////////////////////
<script>
var item = {
"ProductName": "Adult Moddey Dhoo T-Shirt",
"ProductID": "mn-tee-dhoo",
"Categories": ["tshirt",],
"URL": "https://www.manxnostalgia.com/shop/tshirt/adult-moddey-dhoo-tshirt",
"Brand": "Moddey Dhoo"
};
// Track view product
_learnq.push(["track", "Viewed Product", item]);
// Get variants used on product page, add to above item object, send as 'Add to Cart' event
function klaviyoATC() {
let variants = document.getElementsByClassName("variant-select-wrapper");
let variantsInc = 0;
Array.prototype.forEach.call(variants, function(variant, index) {
let elem = variants.item(index);
let variantType = elem.getElementsByTagName('select')[0].getAttribute('data-variant-option-name');
if (!elem.getAttribute('data-text').includes("Select ")) {
item[variantType] = elem.getAttribute('data-text');
variantsInc++;
}
});
if (variantsInc === variants.length) {
item.Price = document.querySelector(".product-price").textContent.replace("£", "");
item.Quantity = document.querySelector(".product-quantity-input").getElementsByTagName('input')[0].getAttribute('value');
_learnq.push(['track', 'Added to Cart', item]);
}
}
document.querySelector(".ProductItem-details .sqs-add-to-cart-button").addEventListener('click', event => klaviyoATC());
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment