hobord
12/28/2017 - 3:57 PM

Send scroll stats to google analytics

Send scroll stats to google analytics

document.addEventListener('scroll', function() {
  var h = document.documentElement,
    b = document.body,
    st = 'scrollTop',
    sh = 'scrollHeight',
    step = 10;


  //Entire document
  var percent = (h[st] || b[st]) / ((h[sh] || b[sh]) - h.clientHeight) * 100;
  var scrollPercent = Math.round(percent);
  scrollPercent = scrollPercent - scrollPercent % step

  if (scrollPercent > window.prevScollPercent || window.prevScollPercent == null) {
    if (window.prevScollPercent == null || typeof(window.prevScollPercent) == 'undefined') {
      for (i = 10; i < scrollPercent; i += 10) {
        ga('send', {
          hitType: 'event',
          eventCategory: 'Navigation',
          eventAction: 'page_scroll',
          eventLabel:  i + '%'
        });
        console.log("page scroll:" + i + '%');
      }
    }
    ga('send', {
      hitType: 'event',
      eventCategory: 'Navigation',
      eventAction: 'page_scroll',
      eventLabel:  scrollPercent + '%'
    });
    console.log("page scroll:" + scrollPercent + '%');
    window.prevScollPercent = scrollPercent;
  }
});