How To Install Scroll Depth Tracker On Your Website Even If You Don’t Know Code

By mike | Google Analytics

Apr 29

No Payment Until Job Is Completed

Any product or service under $200.00 will not require payment until the job is done. When the job is done and paid for, you will get all logins and/or permissions. So it's better than a money back guarantee. 


You don’t have to be a genius to install scroll depth trackers on your website. This is a very important metric, especially if you’re doing advertising on social media sites like Facebook.

Facebook is mostly mobile traffic, and you may get a lot of accidental clicks from fat fingered people like myself.

Now you can measure every visitor, and with this hack you will know who:Mistakes Can Happen

  1. Scrolled 25% of every page on your website
  2. Scrolled 50%
  3. Scrolled 75%
  4. Scrolled to the bottom (100%)

These actions end up getting pushed into your Google Analytics as events, and I always turn my scroll to bottom as a goal. Unless it’s a short page.

It’s important to understand that one little mistake will make it not work, and it’ll take forever to find it.

Take it slow, and double check everything. I made not one, but two mistakes doing this one. Luckily I had this post to look back on and I found my mistakes pretty quick because I was taking screenshots as I went.. I’ll show you each one as I get to it.

Are You New To Google Tag Manager?

If you are, start getting familiar with it. The whole concept of Google Tag Manager is to measure your tags, like:

  1. Google Analytics
  2. Facebook Tracking Pixels
  3. Google Adwords and/or Remarketing Tags

I found many articles out there, but the problem is they are made with the older interface of Tag Manager, so it’s very confusing. Here I will show you with as little details as possible.

Step 1) Be sure you have Google Analytics installed through your tag manager.

If you don’t, it’s very easy to move your existing one.

Step 2) Create Your First Trigger For Your Scroll Depth Tracker

Create New TriggerCreate New Trigger

Click “Triggers” on the left, then click “New“.

Name Your Trigger

Name your trigger “DOM Ready“, select “PageView” for your trigger type and keep “all page views” selected. Click Save.

Step 3) Create Your First Tag

Create New Tag

Click “Tags” on the left, then “New“.

Now you need to copy the following code to your clipboard:

<script>
/*!
 * @preserve
 * jquery.scrolldepth.js | v0.4.1
 * Copyright (c) 2014 Rob Flaherty (@robflaherty)
 * Licensed under the MIT and GPL licenses.
 */
;(function ( $, window, document, undefined ) {
  
  "use strict";

  var defaults = {
    elements: [],
    minHeight: 0,
    percentage: true,
    testing: false
  },

  $window = $(window),
  cache = [];

  /*
   * Plugin
   */

  $.scrollDepth = function(options) {
    
    var startTime = +new Date;

    options = $.extend({}, defaults, options);

    // Return early if document height is too small
    if ( $(document).height() < options.minHeight ) {
      return;
    }

    // Establish baseline (0% scroll)
    sendEvent('Percentage', 'Baseline');

    /*
     * Functions
     */

    function sendEvent(action, label, timing) {
      if (!options.testing) {

        if (typeof(dataLayer) !== "undefined") {
          dataLayer.push({'event':'ScrollDistance', 'eventCategory':'Scroll Depth', 'eventAction': action, 'eventLabel': label, 'eventValue': 1, 'eventNonInteraction': true});

          if (arguments.length > 2) {
            dataLayer.push({'event':'ScrollTiming', 'eventCategory':'Scroll Depth', 'eventAction': action, 'eventLabel': label, 'eventTiming': timing});
          }
        } else {

          if (typeof(ga) !== "undefined") {
            ga('send', 'event', 'Scroll Depth', action, label, 1, {'nonInteraction': 1});

            if (arguments.length > 2) {
              ga('send', 'timing', 'Scroll Depth', action, timing, label);
            }
          }

          if (typeof(_gaq) !== "undefined") {
            _gaq.push(['_trackEvent', 'Scroll Depth', action, label, 1, true]);

            if (arguments.length > 2) {
              _gaq.push(['_trackTiming', 'Scroll Depth', action, timing, label, 100]);
            }
          }
        }

      } else {
        $('#console').html(action + ': ' + label);
      }
    }

    function calculateMarks(docHeight) {
      return {
        '25%' : parseInt(docHeight * 0.25, 10),
        '50%' : parseInt(docHeight * 0.50, 10),
        '75%' : parseInt(docHeight * 0.75, 10),
        // 1px cushion to trigger 100% event in iOS
        '100%': docHeight - 1
      };
    }

    function checkMarks(marks, scrollDistance, timing) {
      // Check each active mark
      $.each(marks, function(key, val) {
        if ( $.inArray(key, cache) === -1 && scrollDistance >= val ) {
          sendEvent('Percentage', key, timing);
          cache.push(key);
        }
      });
    }

    function checkElements(elements, scrollDistance, timing) {
      $.each(elements, function(index, elem) {
        if ( $.inArray(elem, cache) === -1 && $(elem).length ) {
          if ( scrollDistance >= $(elem).offset().top ) {
            sendEvent('Elements', elem, timing);
            cache.push(elem);
          }
        }
      });
    }

    /*
     * Throttle function borrowed from:
     * Underscore.js 1.5.2
     * http://underscorejs.org
     * (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
     * Underscore may be freely distributed under the MIT license.
     */

    function throttle(func, wait) {
      var context, args, result;
      var timeout = null;
      var previous = 0;
      var later = function() {
        previous = new Date;
        timeout = null;
        result = func.apply(context, args);
      };
      return function() {
        var now = new Date;
        if (!previous) previous = now;
        var remaining = wait - (now - previous);
        context = this;
        args = arguments;
        if (remaining <= 0) {
          clearTimeout(timeout);
          timeout = null;
          previous = now;
          result = func.apply(context, args);
        } else if (!timeout) {
          timeout = setTimeout(later, remaining);
        }
        return result;
      };
    }

    /*
     * Scroll Event
     */

    $window.on('scroll.scrollDepth', throttle(function() {
      /*
       * We calculate document and window height on each scroll event to
       * account for dynamic DOM changes.
       */

      var docHeight = $(document).height(),
        winHeight = window.innerHeight ? window.innerHeight : $window.height(),
        scrollDistance = $window.scrollTop() + winHeight,

        // Recalculate percentage marks
        marks = calculateMarks(docHeight),

        // Timing
        timing = +new Date - startTime;

      // If all marks already hit, unbind scroll event
      if (cache.length >= 4 + options.elements.length) {
        $window.off('scroll.scrollDepth');
        return;
      }

      // Check specified DOM elements
      if (options.elements) {
        checkElements(options.elements, scrollDistance, timing);
      }

      // Check standard marks
      if (options.percentage) {        
        checkMarks(marks, scrollDistance, timing);
      }
    }, 500));

  };

})( jQuery, window, document );
jQuery.scrollDepth();
</script>

Don’t worry about all that scientific code. You can thank Robert Flaherty for writing this scroll depth track code. Guys like him make the internet a better place. Just be sure to copy it all.

Copy The Code

Select “custom HTML” and paste that code into the box that appears. For the trigger, select that DOM one we made during step 2.

Once your box looks like mine, click save.

Step 4) Create Event Variables

The good news is you don’t even need to know what that means. Just do the following. We will be creating four events, which is what will be pushed to Google Analytics. It’ll make more sense once we do this.

Create New Variables

Click “variables” on the left, then click “new“.

Event Category

Name your first variable “eventCategory” and out that in the Data Layer Variable Box as well. Pay attention to that capital “C”. I’m not sure if it matters, but when you do this stuff always pay attention to what is lowercase, and what isn’t.

Now click save. We will be doing the same exact thing 3 more times, but with different names:

Event Action

Event Action

Event Label

Event Label Variable

Event Value

Event Value Variable

Now click save, and you should see them all now, just like this:

User Defined Variables

The bottom three have nothing to do with this exercise. That’s me measuring people who watch an embedded YouTube video this same client’s landing page they use for social media.

Step 5) Connect All Of This To Your Already Installed Google Analytics By Creating One More Tag

This is how all of the stuff you just did all gets connected together.

Google Analytics Tracking Code

Log in to your Google Analytics. Click “Admin” on the lower left. Then click “Tracking Info” then “Tracking code“.

Google Analytics Tracking ID

Copy that UA number to your clipboard.

Add second Google Tag

Go back to Google Tag Manager and click “tags”, then “new“.

Select “Universal Analytics” and paste your UA number into the Tracking ID box.

Change “pageview” to “event” in the Track Type Box.

 

Mistake 1: I put “Event Label” in the value box. You’ll see it below. That should obviously be {{eventLabel}}

Scroll Tracking Google Analytics

Click the little folders on the right of each box starting with “category” and enter each of the 4 variables we made a few minutes ago. It’s very obvious what goes where.

See where I circled the Non-Interaction Hit box? This option is up to you. If you keep it at false it will lower your bounce rate dramatically. So it’ll only measure visitors who go to your website and don’t scroll and record them as a bounce. If you set it to true, it won’t affect your bounce rate. I like to keep it at false because I hate the bounce rate metric.

If you change it to true and I visit your website, imagine this. I land on your site and read every word and scroll up and down for twenty minutes. Unless I click another link on your website, I am a bounce with “zero” time on site.

You’re the boss though, so it’s up to you.

Step 6) Adding Final Trigger To Make The Magic Happen

Create Last Trigger

Google Tag Manager will ask you to create a new trigger after you save. Click “yes” and click the “+” sign in the upper right.

Mistake 2: I had a space between Scroll Distance. It needs to be ScrollDistance without a space. This took me a long time to find.

Last Trigger

Name it “Event equals ScrollDistance“, put “ScrollDistance” in the event name box and save it.

Step 7) We Are Done, But We Just Need To Test!

Preview and Test Google Tag Manager

Click the “preview” button on the top right area. After you click, you will see the orange box appear saying “Now Previewing Workspace — Default Workspace“.

Scroll Depth Tracking Test

Now open another tab or a new window and visit the website you just added the tags for. If you don’t see the tag window on the lower part of your screen you are not in preview mode.

Note the three tags fired on this page:

  1. Atlas Motors Analytics (This is their regular Google Analytics that fires on every page).
  2. Atlas Motors YouTube (This is another script I installed which measures how many people watch that video to the end, how many hit the play button and how many pause the video. I love to measure engagement).
  3. Scroll Depth Tracking 1 (This is what we just installed and it’s ready to record some action).

Note that the scroll tracking didn’t fire? I didn’t scroll yet, but the way I test that is simple. I’ll now go back to Google Tag Manager and click the blue “submit” button on the top right. Then I will click “publish“. You can name it in the next box, or just hit “skip“.

Leave Preview Mode

To avoid driving yourself crazy, go back to tag manager and click “leave preview mode“. If you don’t that Tag test will show up every time you visit your website is you’re still signed into Google. It’s very annoying but harmless.

Real Time Test

So now I login to Google Analytics and I’ll click “real time”, then “events”. Open another window or even use your phone and visit your site. There’ll be a 10-second delay, but you’ll see it in action as you scroll. Text your website to a friend and ask them to go on as well and you can see it in action. Click events in the last 30 minutes to see all of what just happened.

Anytime you want to see this data just click “behavior” and “events”. I like to set visits who scrolled 100% as a goal.

That’s is it, it’s over. You are done!

 

 

 

 

 

 

 

 

 

Copy The Code

Follow

    About the Author

    I've been working in digital marketing since 1994. I'm the original founder of Showroom Logic based out of Miami Florida. I moved back to Carver Massachusetts to be closer to my family. After my second winter back, I am questioning my sanity.