This articles covers the way to track page scrolling activity without jQuery in a single page application using a Javascript extension.

Setup

Add a JavaScript extension. Set the scope to After Tag Extensions. Then paste the following into the code section:

//general variables
var body = document.body;
var html = document.documentElement;
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat');

// use predefined scrollTracker function if available, otherwise create it on first page view
scrollTracker = window.scrollTracker || function () {
        
        // get current y offset
        // https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY
        var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
        var percent = Math.round((y / window.height) * 100);
        var shouldTrack = false;

        // reached or exceeded mark - 25%, 50% or 75%
        if (percent >= window.mark && !window.trackedSteps.has(window.mark)) {
            window.trackedSteps.add(window.mark);
            shouldTrack = true;
        }

        // 100%
        if (y + window.innerHeight >= window.height  && !window.trackedSteps.has(100)) {
            window.mark = 100;
            window.trackedSteps.add(window.mark);
            shouldTrack = true;
        }
        // build and send utag.link event
        if (shouldTrack) {
            var data = {
                tealium_event: 'user_scroll',
                eventCategory: 'Behavior',
                eventAction: 'Scroll',
                eventLabel: window.mark
            };
            utag.link(data);
            
            // increment mark variable to prevent duplicate fires for the same percentage
            window.mark = window.mark < 100 ? window.mark + window.step : window.mark;
        }
    };
    
if (document.readyState !== 'loading') {
    
    window.removeEventListener('scroll', scrollTracker, true);
        
    // Reset tracking variables on new page view
    window.trackedSteps ? window.trackedSteps.clear() :  window.trackedSteps = new Set();
    window.step = 25;
    window.mark = 0 + step;
    window.height = Math.max(body.scrollHeight, body.offsetHeight,
            html.clientHeight, html.scrollHeight, html.offsetHeight);
            
    window.addEventListener('scroll', scrollTracker, true);
} 

You should review and update the parameters passed to utag.link listed above. Make sure these align with the Data Layer variables you have defined in your profile for your tag.  

The scope After Tag Extensions only works if at least one tag in the profile requires DOM ready to fire. Also, for Internet Explorer, this code is only backwards compatible to version 9+. 

Version history
Last update:
‎03-03-2021 02:55 PM
Updated by: