Skip to content

Instantly share code, notes, and snippets.

@prabapro
Created January 6, 2022 17:30
Show Gist options
  • Save prabapro/5a04b1efbe19ee9f6c0c98bd17d27c5c to your computer and use it in GitHub Desktop.
Save prabapro/5a04b1efbe19ee9f6c0c98bd17d27c5c to your computer and use it in GitHub Desktop.
GTM - Exact scroll percentage using jQuery

Check if jQuery is enabled on the site - running the below snippet on the browser console will return the result.

(function() {
    if (window.jQuery) {  
        // jQuery is loaded
        return("Yeah! JQuery loaded");
    } else {
        // jQuery is not loaded
        return("Nope, Doesn't Work");
    }
})();

Create a custom javascript variable in GTM

function() {
  var winHeight = jQuery(window).height();
  var docHeight = jQuery(document).height();
  var scrollTop = jQuery(window).scrollTop(); //NaN or zero at top
  var trackLength = docHeight - winHeight;
  var pctScrolled = Math.floor(scrollTop / trackLength * 100);
  return pctScrolled;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment