Skip to content Skip to sidebar Skip to footer

Get Percentage Scrolled Of An Element With Jquery

I'm trying to get an div to animate 0% - 100% relative to the percentage scrolled of an element. Now I've set up a few variables, but I'm having trouble trying to calculate the he

Solution 1:

Demo

Your problem is the same as How to get horizontal scrolling percentage of an HTML element in JavaScript?, but vertically.

Then, to get the vertically scrolled percentage, use

/*  JS  */var scrollPercentage = 100 * containeR.scrollTop / (containeR.scrollHeight-containeR.clientHeight); 
/*jQuery*/var scrollPercent = 100 * $(containeR).scrollTop() / ($(containeD).height() - $(containeR).height());

In your case, containeR = window; containeD = document:

var scrollPercent = 100 * $(window).scrollTop() / ($(document).height() - $(window).height());

Solution 2:

Ok I see what you are trying to achieve....in fact I just did something very similar. Most solutions I found out there also were only for full page examples with window or document properties. Instead I needed this in a specific div which in my case was actually used to update the horizontal position of another div.

First, you are going to want the scroll event attached to your $('.post')

Next, the height of the $('.content') is going to equal your actual Scroll Height

Lastly, apply your percentage formula : (Y / (scrollHeight - postHeight)) * 100 = scrollPercent

So instead of using document or window attributes your code should be as follows:

$('.post').scroll(function() {
  var currY = $(this).scrollTop();
  var postHeight = $(this).height();
  var scrollHeight = $('.content').height();
  var scrollPercent = (currY / (scrollHeight - postHeight)) * 100;
});

You can find the fiddle here: JS Fiddle For Div Scroll Percentage

The current project where I have implemented this is located here: Vertical Scroll Drives Horizontal Position

I hope this solves your problem :)

Solution 3:

Let's say you want to keep track of the scroll of some document found in some IFrame in your page.

object.addEventListener("scroll", documentEventListener, false);

Then your event listener should look like this:

functiondocumentEventListener(){
  var currentDocument  = this;
  var docsWindow       = $(currentDocument.defaultView); // This is the window holding the documentvar docsWindowHeight = docsWindow.height(); // The viewport of the wrapper windowvar scrollTop        = $(currentDocument).scrollTop(); // How much we scrolled already, in the viewportvar docHeight        = $(currentDocument).height();    // This is the full document height.var howMuchMoreWeCanScrollDown = docHeight - (docsWindowHeight + scrollTop);
  var percentViewed = 100.0 * (1 - howMuchMoreWeCanScrollDown / docHeight);
  console.log("More to scroll: "+howMuchMoreWeCanScrollDown+"pixels. Percent Viewed: "+percentViewed+"%");
}

Post a Comment for "Get Percentage Scrolled Of An Element With Jquery"