Created
September 23, 2021 19:39
-
-
Save maestrojed/a09305f2eb36faf0a91b492fbd5a47d5 to your computer and use it in GitHub Desktop.
Track when CTAs are visibile and record them as impressions in Google Analytics.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Drupal.behaviors.ctaImpressions = { | |
attach: function (context, settings) { | |
//A JS Script to | |
// find each Linkwell CTA; | |
// for each unique CTA found track when it becomes visible; | |
// when it becomes visible push a non-interactive event to GA; | |
// no longer track this CTA's visibility to prevent duplicate GA events and hopefully lessen the performance impact; | |
//The action to take on each observation of a CTA | |
let callback = (entries, observer) => { | |
entries.forEach(entry => { | |
//get the cta data | |
var campaignBase = entry.target.getAttribute('data-campaignbase'); | |
var campaignData = entry.target.getAttribute('data-campaigndata'); | |
if(entry.isIntersecting) { | |
// Push the GA Event | |
if(typeof gtag === 'function') { | |
gtag('event', 'CTA Impression', { event_category: campaignBase, event_label: campaignData, transport_type: 'beacon', 'non_interaction': true }); | |
//Unobserve this now that its been impressed, we do not want to keep impressing it every times it scrolls by. | |
observer.unobserve(entry.target); | |
} | |
} | |
}); | |
}; | |
//These options determine when a CTA element should be considered impressed. | |
// root null means when the viewport is scrolled | |
// threshold means with at least 70% of the cta is visible. | |
let options = { | |
root: null, | |
rootMargin: '0px', | |
threshold: 0.7 | |
}; | |
//Start the observer | |
let observer = new IntersectionObserver(callback, options); | |
//Find all CTA Elements in the page and observe them for visibility | |
let ctas = document.querySelectorAll('.linkwell-cta'); | |
// Track that we have impressed this campaign to prevent duplicate | |
// impressions (some ctas are composed of 2 links, each have this | |
// class, but this is considered 1 cta) | |
var campaignsImpressed = []; | |
ctas.forEach(cta => { | |
//If a CTA with the same campaignBase is already being observed, do not observe this one. | |
var campaignBase = cta.getAttribute('data-campaignbase'); | |
if(campaignsImpressed.includes(campaignBase)===false) { | |
observer.observe(cta); | |
campaignsImpressed.push(campaignBase); | |
} | |
}); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment