console.log('article');
if (!collection.length) collection= [];
var allProducts = collection.map(function(product, index) {
return {
name: product.title.replace("'", ''),
id: product.variants[0].sku,
price: product.price / 100,
brand: product.vendor,
position: index,
list: "Search Results",
handle: product.handle
};
});
var visibleProducts = [];
Array.prototype.slice.call(document.querySelectorAll('a[href*="/products/"]')).forEach(function(item) {
var arr = item.href.split('/products/');
var handle = arr[arr.length-1];
if (!allProducts.length) return;
var matchingProduct = allProducts.filter(function(product) {
return product.handle === handle;
});
if (!matchingProduct.length) return;
if (visibleProducts.indexOf(matchingProduct[0]) == -1) {
visibleProducts.push(matchingProduct[0]);
}
})
window.dataLayer.push({
event: 'searchResults',
ecommerce: {
currencyCode: "USD",
actionField: { list: "Search Results" },
impressions: visibleProducts,
}
});
Array.prototype.slice.call(document.querySelectorAll('a[href*="/products/"]'))
.forEach(function(select) {
select.addEventListener('click', handleProductClick);
});
function getClickedProductHandle(element) {
var arr = element.href.split('/products/');
return arr[arr.length-1];
}
function handleProductClick(event) {
if(typeof allProducts == "undefined") return;
var target = event.target.matches('a[href*="/products/"]')
? event.target
: event.target.closest('a[href*="/products/"]');
var handle = getClickedProductHandle(target);
var clickedProduct = allProducts.filter(function(product) {
return product.handle === handle;
});
if (clickedProduct[0]) delete clickedProduct[0].list;
if (clickedProduct[0]) delete clickedProduct[0].handle;
window.dataLayer.push({
'event': 'productClick',
'ecommerce': {
currencyCode: "USD",
'click': {
'actionField': {'list': getPageType()},
'products': clickedProduct
}
},
});
}
}, false);