Search code examples
javascriptfacebooksquarespace

Add FB pixel event code into button - Squarespace


I am new to squarespace. My client wants to track the page views for this, I have injected Base pixel code to header of all pages and it worked perfect,

But now she wants to track , if the user click on any buy button on this page

I have no idea how to inject facebook pixel code to a button in squarespace, any idea or reference would be highly appreciated . Thanks


Solution

  • It sounds like what you want to do is add an "Event Code" either:

    • A) to the page that the user sees after clicking the button, or
    • B) to the button itself.

    If you're going with the prior option (A), then you'd want to make sure that the page upon which the user lands does in fact indicate the event you're tracking and that users do not arrive to that page for any other purpose. That is why I would lean towards the latter option (B).

    You can read more about adding an event code here, and here, but in summary:

    Events are actions that happen on your website, either as a result of Facebook ads (paid) or organic reach (unpaid). The event code lets you track those actions and leverage them in advertising.

    There are two types of events you can send:

    • Standard events. 9 events we're able to track and optimize your ads for without any additional actions...
    • Custom events. Actions that are important to your business, but that you can’t use for tracking and optimization without additional action...

    ...

    enter image description here

    If you were to consider these buttons to be an "Add to Cart" type-of-action, then you'd use the AddToCart event. To do so, you could use Javascript similar to the following:

    <script>
        window.Squarespace.onInitialize(Y, function() {
            var btns = document.getElementsByClassName("sqs-block-button-element");
            var i;
            for (i=btns.length-1; i>=0; i--) {
                btns[i].addEventListener("click", function() {
                    fbq("track", "AddToCart");
                });
            }
        });
    </script>
    

    You could inject this code using per-page code injection or via site-wide code injection. I would recommend the prior, otherwise all buttons on your site will execute the fbq event code, which is probably undesirable.

    Regardless of whether you use site-wide or per-page injection, you may want to better target the buttons using a more specific selector. For example, you could use querySelectorAll and target by href attribute. However, if you use per-page injection, the code I supplied should work; it will apply it to every button on that page.