Scroll Depth Events in the dataLayer
Pushes scroll_depth events to the Google Tag Manager dataLayer when visitors scroll 25, 50, 75 and 90 percent of a page, to measure how far content is read.
Opens WPIDE on
Code
add_action( 'wp_footer', function () {
?>
<script>
(function () {
var marks = [25, 50, 75, 90], sent = {};
window.dataLayer = window.dataLayer || [];
function check() {
var doc = document.documentElement;
var max = doc.scrollHeight - window.innerHeight;
if (max <= 0) { return; }
var percent = Math.round((window.pageYOffset || doc.scrollTop) / max * 100);
marks.forEach(function (mark) {
if (percent >= mark && !sent[mark]) {
sent[mark] = true;
window.dataLayer.push({ event: 'scroll_depth', scroll_percent: mark, page_path: location.pathname });
}
});
}
var ticking = false;
window.addEventListener('scroll', function () {
if (ticking) { return; }
ticking = true;
window.requestAnimationFrame(function () { check(); ticking = false; });
}, { passive: true });
})();
</script>
<?php
} );
Notes
In GTM, create a Custom Event trigger for "scroll_depth" and read the percent value from the dataLayer variable "scroll_percent".
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.