Measuring User Scroll with jQuery

It’s super easy to measure the amount a user scrolls down with jQuery. In fact, it’s not hard to grab a percentage of the page the user has scrolled either. Which means you can add some interactive portions to your page depending on how much the user has scrolled down your site. It’s just another way to grab user attention and define a rich interactive environment for your users.

To take action on user scroll do something like this:

$(document).scroll(function(e){

	// do something on user scroll here

});

To get the amount the user has scrolled:

var scrollAmount = $(window).scrollTop();

To get the height of the page:

var documentHeight = $(document).height();

To get the percentage of the page height the user has scrolled:

var scrollPercent = (scrollAmount / documentHeight) * 100;

Let’s say I wanted to do something when a user gets halfway down my page:

$(document).scroll(function(e){

	// grab the scroll amount and the window height
    var scrollAmount = $(window).scrollTop();
    var documentHeight = $(document).height();

    // calculate the percentage the user has scrolled down the page
    var scrollPercent = (scrollAmount / documentHeight) * 100;

	if(scrollPercent > 50) {
		// run a function called doSomething
		doSomething();
	}

	function doSomething() { 

		// do something when a user gets 50% of the way down my page

	}

});

Just wanted to share some helpful (and simple) ways to monitor user interaction.

2 thoughts on “Measuring User Scroll with jQuery

  1. Brilliant. Spent a week looking for the right way to do this just as you wrote it. I didn’t think there was a way to get the percentage.

Leave a Reply

Your email address will not be published. Required fields are marked *