Reputation: 41
I'm trying to add a Facebook pixel event -- "ViewContent" -- to my Squarespace site. I have one page with one button, and I want to fire the event on the button click. It feels like it should be simple, but I'm consistently getting an error in Facebook Pixel Helper with my current setup.
I'm referencing this post: Add FB pixel event code into button - Squarespace
And as recommended in the answer, I'm using a per-page code injection in the header on this page: https://www.wearpapercrane.com/survey
This is what I have --
<script>
(function() {
var btns = document.getElementsByClassName("sqs-block-button-element");
var i, I;
for (i=0, I=btns.length; i<I; i++) {
btns[i].addEventListener("click", function() {
fbq("track", "ViewContent");
});
}
})();
</script>
But here's what I get on the other end when I use Facebook Pixel Helper to validate --
(This is after the click, by the way ... the button opens the link in a separate tab, so this is going back to the page after the click and looking at Pixel Helper).
Is there something I'm missing that is resulting in this error?
I have the pixel installed and I have a "lead" event working properly on another page (using Squarespace's Form Embed feature), so I'm pretty sure it's a problem with this specific code injection.
Would love any and all recommendations. Thank you!!
Upvotes: 4
Views: 1062
Reputation: 3687
The event is not firing because the answer you referenced (which I wrote) did not account for the fact that, when injecting the code via header injection (site-level or page-level), one must wait for the DOM to be loaded before attaching events to the elements.
The answer you have referenced has been updated, notably the following section:
<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>
Upvotes: 2