0

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.

0

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
    };
}
3
  • Inline JS events is bad practice :(
    – Ben Crook
    Jan 5 '18 at 10:15
  • @BenCrook Thanks for the reminder, yes it is bad practice for multiple reasons. I will add to the answer to give another option.
    – tbedner
    Jan 5 '18 at 14:47
  • As a further improvement, rather than using window.onload you can just add domReady! as a dependency in require and your JS file will only load once the DOM has finished rendering.
    – Ben Crook
    Jan 5 '18 at 15:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.