Skip to content

Instantly share code, notes, and snippets.

@mbaersch
Created November 23, 2021 13:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbaersch/627602ba20530c8de194f982188ed6ef to your computer and use it in GitHub Desktop.
Save mbaersch/627602ba20530c8de194f982188ed6ef to your computer and use it in GitHub Desktop.
Custom HTML Tag for Google Tag Manager to create markers in main content for triggering "content consumption" events
<script>
/*
This code can be used as a Custom HTML tag in Google Tag Manager to create invisible "marker lines"
every x percent inside a container (selected via CSS selector) that holds the main content of a page
(like a blog post).
You can then use visibility triggers for the marker lines (selected by name or class) in GTM in order
to fire event tags for Google Analytics or any other tool to measure "content consumption" without
having to rely inaccurate scroll tracking.
if you need the current percentage for the different lines and use just one visibility trigger
(by class name) for several steps, you can utilize an auto event variable and extract the attribute
"data-content-visibility-percentage" from the current element.
*/
/****************************************************************************/
var contentElementSelector = ".entry-content"; //CHANGE THIS: CSS Selector for main content container
var contentMarkerName = "contentMarkerLine"; //optional: define name for marker events
var contentMarkerClass = "contentMarkerLine"; //optional: change class name for selecting elements by class
var contentMarkerSteps = [25,50,75,90,100]; //set steps (in percent of element height) as array
var contentMarkerDebug = false; //activate for debugging: "true" makes marker lines visible in red on the page, when tag is fired
/****************************************************************************/
var el = document.querySelector(contentElementSelector);
if (el) {
el.style.position = "relative";
contentMarkerSteps.forEach(function(s){
var line = document.createElement("div");
line.id = contentMarkerName + s.toString();
line.style.position = "absolute";
line.style.height = "1px";
line.className = contentMarkerClass;
line.style.top = s.toString() + '%';
line.style.width = "100%";
line.setAttribute('data-content-visibility-percentage', s);
if (contentMarkerDebug === true) line.style.background = 'red';
el.appendChild(line);
});
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment