I'm trying to retrieve the data attributes from the cart but it's not working.
I also would like to know if there's a way to shorten the code.
HTML:
<div id="product-listing" class="hidden">
<div>
<img src="img1.jpg" />
<div class="description">Lagavulin 16 Year Old</div>
<button class="add-to-cart"
data-product-id="1"
data-product-title="Lagavulin 16 Year Old" data-category="Scotch">
Add To Cart
</button>
Vanilla js:
function onPageLoad(event) {
var title = document.getElementsByTagName("title")[0].innerText;
console.log({
event_name: "page loaded",
page_title: title,
});
}
var photo = document
.getElementsByClassName("add-to-cart")
.getAttribute("data-product-id");
for (var i = 0; i < photo.length; i++) {
photo[i].onclick = function() {
console.log({
event_name: "add_to_cart",
product_id: data-product-id,
product_title: data-product-title,
});
}
};
This should work:
Array.from(document.getElementsByClassName("add-to-cart")).forEach(x => x.onclick = () => console.log({
event_name: "add_to_cart",
product_id: x.getAttribute("data-product-id"),
product_title: x.getAttribute("data-product-title")
}));
<button class="add-to-cart" data-product-id="1" data-product-title="Lagavulin 16 Year Old" data-category="Scotch">Add To Cart</button>
<button class="add-to-cart" data-product-id="2" data-product-title="Some other Scotch" data-category="Scotch">Add To Cart</button>
You were not properly iterating over the elements returned by getElementsByClass and also not using element.getAttribute("") correctly.
To make it shorter I used streams.
Try this way:
var photo = document
.getElementsByClassName("add-to-cart");
for (var i = 0; i < photo.length; i++) {
photo[i].onclick = function() {
console.log({
event_name: "add_to_cart",
product_id: photo[i].getAttribute("data-product-id"),
product_title: photo[i].getAttribute("data-product-title"),
});
}
};
Try this
var photo = document.querySelectorAll('.add-to-cart');
photo.forEach(function(button){
button.addEventListener('click',function(){
console.log(this.getAttribute('data-product-id'));
},{passive:true});
});