powerdown
powerdown

Reputation: 47

Set up Facebook pixel to fire on click event

I want to set up a pixel to fire when a button is clicked. Facebook offers some info here on doing this very thing, but I am a javascript novice and can't figure it out. How does one use the info on that page to alter the code below to fire on a button click? Here is the base code snippet:

<script>(function() {
var _fbq = window._fbq || (window._fbq = []);
if (!_fbq.loaded) {
var fbds = document.createElement('script');
fbds.async = true;
fbds.src = '//connect.facebook.net/en_US/fbds.js';
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(fbds, s);
_fbq.loaded = true;
}
})();
window._fbq = window._fbq || [];
window._fbq.push(['track', 'MyPixelID', {'value':'0.01','currency':'USD'}]);
</script>

Upvotes: 2

Views: 9563

Answers (1)

user1932079
user1932079

Reputation:

You're just missing the function to call which "fires" the pixel and the button...

Javascript:

function myButtonClicked(val, curr) {
  //Do your thing
  window._fbq.push(['track', 'MyPixelID', {'value':val,'currency':curr}]);
}

And the button:

<button onClick="myButtonClicked(val, curr);" />

Or a link styled to look like a button:

<a href="javascript:myButtonClicked(val, curr);">Text</a>

And, continuing on per the comments:

<a href="http://example.com" onclick="myButtonClicked(val, curr);">Text</a>

Note: In the line above, the onclick is processed first, then since propagation is not cancelled by any means, the href navigation executes.

Upvotes: 6

Related Questions