Hello i'm trying to track a onclick event from my add to cart button, so i have a script in
<head>
<script type="text/javascript">
var button = document.getElementById('addToCartButton');
button.addEventListener(
'click',
function () {
fbq('track', 'AddToCart', {
content_name: 'Really Fast Running Shoes',
content_category: 'Apparel & Accessories > Shoes',
content_ids: ['1234'],
content_type: 'product',
value: 4.99,
currency: 'USD'
});
},
false
);
</script>
</head>
<button
id="addToCartButton"
class="mt-5 w-full rounded-xl bg-vert p-2 py-3.5 font-bold text-white"
>ADD TO CART
</button>
The problem is : when i refresh the website, the event is working without click on button If someone can help me, thanks
I don't think the event is working. I think you get confused between the errors, but don't worry.
The thing is that the script tag should be in the body specially in the bottom of the body and not in the head so all the tags will be first loaded than can JavaScript get the button for you but how are doing it is that you prepare your script before the HTML tags are being loaded, so JavaScript can't find them.
<body>
<button id="addToCartButton" class="mt-5 w-full rounded-xl bg-vert p-2 py-3.5 font-bold text-white">ADD TO CART</button>
<script type="text/javascript">
var button = document.getElementById('addToCartButton');
button.addEventListener(
'click',
function () {
fbq('track', 'AddToCart', {
content_name: 'Really Fast Running Shoes',
content_category: 'Apparel & Accessories > Shoes',
content_ids: ['1234'],
content_type: 'product',
value: 4.99,
currency: 'USD'
});
},
false
);
</script>
</body>