Pixel Events in Buttons and Advanced Scenarios - Facebook Pixel
Total Page:16
File Type:pdf, Size:1020Kb
3/6/2018 Pixel Events in buttons and Advanced Scenarios - Facebook Pixel ☰ Analytics My Apps On This Page Marketing API Version v2.12 Pixel Events in buttons and Advanced Scenarios Edit Typically you track conversions and events using Related Topics Facebook Pixel by loading it with a page and firing Using the Pixel Standard Events such as ViewContent or Purchase. Pixel Events However, you may need additional work in some cases. For example: Single Page Applications where it's impractical to load the Pixel multiple times Tracking clicks on buttons Tracking that the user read an entire article Facebook Pixel can work on those cases with some additional code. This page will describe a few of those cases. How it works? Tracking clicks on Button Triggering events based on visibility Triggering events based on page length Delayed Pixel Fires Triggering events based on articles viewed per session Selective event tracking with multiple pixels How it works? Facebook Pixel has three basic parts: 1. Loading code, which downloads the actual pixel code from Facebook's servers 2. Initialization code ‑ Defines pixel ID and fires a PageView event using the fbq function 3. noscript pixel ‑ a fallback for cases when javascript is disabled https://developers.facebook.com/docs/facebook-pixel/events-advanced-use-cases/v2.12#buttonclicks 1/11 3/6/2018 Pixel Events in buttons and Advanced Scenarios - Facebook Pixel The fbq function can be used to track additional actions without the need to repeat the steps above. All examples in this page assume the default pixel code has already been loaded. <!-- Facebook Pixel Code --> <script> !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n; n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window, document,'script','https://connect.facebook.net/en_US/fbevents.js'); // Insert Your Custom Audience Pixel ID below. fbq('init', '<FB_PIXEL_ID>'); fbq('track', 'PageView'); </script> <!-- End Facebook Pixel Code --> You can improve Pixel effectiveness if you track all PageView events. We do not recommend removing the initial PageView event from your website when tracking additional events. Tracking clicks on Buttons Suppose you have an e‑commerce website and your "Add to Cart" button does not navigate to a new page. You may want to activate an event when the button is clicked. In this example, we will activate a ViewContent standard event on page load. When someone clicks "Add to Cart" button, we will activate an AddToCart standard event. To do this, first load Facebook Pixel code that you want to fire on page load: <!-- Facebook Pixel Code --> <script> fbq('track', 'ViewContent', { content_name: 'Really Fast Running Shoes', content_category: 'Apparel & Accessories > Shoes', content_ids: ['1234'], content_type: 'product', value: 0.50, currency: 'USD' }); </script> <!-- End Facebook Pixel Code --> https://developers.facebook.com/docs/facebook-pixel/events-advanced-use-cases/v2.12#buttonclicks 2/11 3/6/2018 Pixel Events in buttons and Advanced Scenarios - Facebook Pixel Then fire AddToCart either on a new page load or on the click of an Add To Cart button. There are multiple ways to handle clicks on buttons. Here's an example adding an eventListener to a button. <!-- Somewhere there is a button that performs Add to Cart --> <button id="addToCartButton">Add To Cart</button> <!-- Add Pixel Events to the button's click handler --> <script type="text/javascript"> var button = document.getElementById('addToCartButton'); Was this document helpful? button.addEventListener( 'click'Yes ,Y es, but... No function() { fbq('track', 'AddToCart', { content_name: 'Really Fast Running Shoes', content_category: 'Apparel & Accessories > Shoes', content_ids: ['1234'], content_type: 'product', value: 4.99, currency: 'USD' }); }, false ); </script> There are many ways you can handle click events; Make sure you do always call fbq function after the click. Triggering events based on visibility For this example, suppose you have a blog and want to track users who read the entire content of an article. There's no action from the user other than scrolling to the end of the page. Here's the sample HTML for a page where the pixel loads: <!DOCTYPE html> <html> <head> <!-- Facebook Pixel Code --> <script> !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod? n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n; n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0; t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window, https://developers.facebook.com/docs/facebook-pixel/events-advanced-use-cases/v2.12#buttonclicks 3/11 3/6/2018 Pixel Events in buttons and Advanced Scenarios - Facebook Pixel document,'script','https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '<FB_PIXEL_ID>'); fbq('track', "PageView"); </script> <noscript><img height="1" width="1" style="display:none" src="https://www.facebook.com/tr?id=<FB_PIXEL_ID>&ev=PageView&noscript=1" /></noscript> <!-- End Facebook Pixel Code --> </head> <body> <h1>Scroll Page until the Lead event is fired</h1> <div style="height: 120vh; width: 100vw; background-color: #00f;"></div> <h1 id="fb-fire-pixel">Lead event will fire when this phrase enters the screen</h <div style="height: 120vh; width: 100vw; background-color: #000;"></div> </body> </html> When the h1 element with id=fb-fire-pixel appears, we should fire the Lead standard event. To verify an element is visible on screen, we add the following code to the page: // This code should be loaded together with Facebook Pixel var executeWhenElementIsVisible = function(dom_element, callback) { if (!(dom_element instanceof HTMLElement)) { console.error('dom_element must be a valid HTMLElement'); } if (typeof callback !== 'function') { console.error( 'Second parameter must be a function, got', typeof callback, 'instead', ); } function isOnViewport(elem) { var rect = elem.getBoundingClientRect(); var docElem = document.documentElement; return ( rect.top >= 0 && rect.left >= 0 && rect.bottom <= (window.innerHeight || docElem.clientHeight) && rect.right <= (window.innerWidth || docElem.clientWidth) ); https://developers.facebook.com/docs/facebook-pixel/events-advanced-use-cases/v2.12#buttonclicks 4/11 3/6/2018 Pixel Events in buttons and Advanced Scenarios - Facebook Pixel } var executeCallback = (function() { var wasExecuted = false; return function() { if (!wasExecuted && isOnViewport(dom_element)) { wasExecuted = true; callback(); } }; })(); window.addEventListener('scroll', executeCallback, false); }; After that, we need to define how to fire the pixel when the element is visible on screen: // Get the element that should be visible to trigger the pixel fire var element = document.getElementById('fb-fire-pixel'); // Then, set the event to be tracked when element is visible // Note that second parameter is a function, not a function call executeWhenElementIsVisible(element, function() { fbq('track', 'Lead'); }); Triggering events based on page length or percentage For this example, suppose you want to track users who read up to a length or percentage of the page. There's no action from the user other than scrolling to the desired page length or percentage. This first example is to track the length of the page which the user has read. In the example, we are firing off the lead pixel when user has read up to 500px length of the page. var executeWhenReachedPageLength = function(length, callback) { if (typeof length !== 'number') { console.error( 'First parameter must be a number, got', typeof length, 'instead', ); } https://developers.facebook.com/docs/facebook-pixel/events-advanced-use-cases/v2.12#buttonclicks 5/11 3/6/2018 Pixel Events in buttons and Advanced Scenarios - Facebook Pixel if (typeof callback !== 'function') { console.error( 'Second parameter must be a function, got', typeof callback, 'instead', ); } function getWindowLength() { return window.innerHeight || (document.documentElement || document.body).clientHeight; } function getCurrentScrolledLengthPosition() { return window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scroll } var executeCallback = (function() { var wasExecuted = false; return function() { if (!wasExecuted && getCurrentScrolledLengthPosition() > length) { wasExecuted = true; callback(); } }; })(); if (getWindowLength() >= length) { callback(); } else { window.addEventListener('scroll', executeCallback, false); } }; executeWhenReachedPageLength(10, function() { fbq('track', 'Lead'); }); This second example is to track the percentage of the page which the user has read. In the example, we are firing off the lead pixel when user has read 75% of the page. var executeWhenReachedPagePercentage = function(percentage, callback) { if (typeof percentage !== 'number') { console.error( 'First parameter must be a number, got', typeof percentage, https://developers.facebook.com/docs/facebook-pixel/events-advanced-use-cases/v2.12#buttonclicks 6/11 3/6/2018 Pixel Events in buttons and Advanced Scenarios - Facebook Pixel 'instead', ); } if (typeof callback !== 'function') { console.error( 'Second parameter must be a function, got', typeof callback, 'instead', ); } function getDocumentLength() { var D = document; return Math.max( D.body.scrollHeight, D.documentElement.scrollHeight, D.body.offsetHeight,