Magento – How to add onClick event to add to cart button

addtocartcartfacebookmagento-2.1.9

Magento version 2.1.9

I want to use facebook pixel on my magento site. I want to add onclick event to all "add to cart" buttons.

Thank you in advance.

Best Answer

If you are looking to add it to the product view, you can go to

app/code/Magento/Catalog/view/frontend/templates/product/view/addtocart.phtml

and add your onclick event to the button element around line 32.

It is bad practice to add inline js - hat tip to Ben Crook - (see here). An alternative would be to add the following to a js file:

window.onload = function () {
    document.getElementById("product-addtocart-button").onclick = function () {
        // Add Facebook Pixel Event
    };
}
Related Topic