Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Get the current percentage of scroll in an element(not the document) ?

Hi,

I try to find the mathematics calcul to have the scroll percentage of an element? BUT NOT the entire page, just an element. It can be a small image, or a big block.

So when you scroll, and you start to see the element at the bottom the percentage should be around 1% and when the element is almost disappear in the top it should be around 99%.

I was not able to find the formula for this case, only for the scroll percentage of the complete document.

Thanks. :)

3 Answers

In case someone is interested by this, I think I found it...

var percentage = (viewportBottomX - elementTopX) / ((viewportHeight + elementHeight) / divider);

Hey Geoffrey,

You would get the scrollable height minus the display area and then divide the scroll top by this number.

The code below is in pure Javascript and works fine in Chrome (haven't cross browser checked). It would also be a lot quicker in jQuery, you should be able to copy and paste the below straight into a html file to see it work.

Copy thanks to hipsum.co. ;)

  <style>
    *                        { box-sizing:border-box; }
    html                     { font-size:10px; }
    body                     { margin:0; padding:0; font:1.6rem/1 arial !important; background-color:#F1F1F1 !important; }
    #percent                 { margin:50px auto 0; width:500px; font-size:3rem; text-transform:uppercase; text-align:center; }
    #scroller                { margin:10px auto 0; padding:10px 20px; width:500px; height:300px; overflow-y:scroll; background-color:#FFF; }
  </style>

  <p id="percent">Percent : 0%</p>
  <div id="scroller" onscroll="scrolling()">
    <p>Pop-up forage distillery bitters, XOXO meditation tumblr four loko williamsburg vaporware gluten-free readymade. Poke try-hard DIY, quinoa hexagon man braid gluten-free microdosing keffiyeh green juice swag intelligentsia bicycle rights ethical. Thundercats fam 3 wolf moon quinoa ramps cliche typewriter master cleanse taxidermy. DIY air plant hammock, humblebrag deep v jean shorts seitan ennui pug tumeric chia. 8-bit mixtape kickstarter bushwick tumeric, edison bulb flexitarian fashion axe tousled poke intelligentsia crucifix hell of. Narwhal waistcoat ugh green juice small batch. Cronut gentrify VHS lo-fi. Hoodie kogi wolf jianbing, DIY hammock portland cloud bread listicle la croix marfa mlkshk thundercats. La croix yuccie distillery tousled twee, wolf lomo pour-over chambray try-hard. Pabst yuccie pickled, waistcoat kale chips copper mug coloring book woke kombucha everyday carry kitsch poke offal. Plaid chia palo santo edison bulb swag, normcore forage distillery kickstarter. Bicycle rights schlitz taiyaki before they sold out. Live-edge celiac blog tumeric whatever keffiyeh crucifix heirloom.</p>
    <p>Fashion axe green juice kickstarter, keffiyeh pinterest semiotics kombucha literally bushwick. Salvia raw denim vice twee meditation offal franzen flannel sriracha chicharrones biodiesel aesthetic. Four loko salvia letterpress pinterest godard. Mixtape hoodie messenger bag semiotics lomo asymmetrical, woke synth echo park banjo deep v pug tote bag sustainable blue bottle. Ugh kombucha edison bulb, heirloom chicharrones street art iPhone locavore irony affogato narwhal craft beer bespoke knausgaard. Knausgaard migas woke messenger bag trust fund, flannel narwhal master cleanse tilde +1 mixtape. Leggings bespoke artisan fashion axe +1 marfa biodiesel blue bottle pop-up irony hashtag single-origin coffee austin la croix farm-to-table. Fashion axe locavore poke, hammock helvetica cliche PBR&B pabst jianbing. Blue bottle literally air plant, distillery roof party migas lo-fi celiac. Godard brooklyn pabst four loko narwhal.</p>
    <p>Single-origin coffee tousled waistcoat church-key blue bottle austin intelligentsia tilde chicharrones woke. Street art paleo scenester, beard viral pitchfork chicharrones. Pug paleo mlkshk schlitz everyday carry messenger bag pok pok cornhole banh mi street art raw denim portland ennui. 90's vice cronut neutra. Pok pok gochujang hot chicken lomo four dollar toast, vexillologist vegan celiac. Meditation brooklyn neutra pug mumblecore snackwave. Activated charcoal affogato selvage brunch poutine hell of bitters celiac. Brunch bushwick vice chambray, austin butcher vinyl deep v hoodie shaman next level stumptown four loko fingerstache microdosing. Brooklyn vice kombucha unicorn, wayfarers retro photo booth lo-fi post-ironic mlkshk truffaut freegan.</p>
  </div>

  <script>
    const scroller = document.getElementById('scroller');

    function scrolling() {
      let height = scroller.clientHeight;
      let scrollHeight = scroller.scrollHeight - height;
      let scrollTop = scroller.scrollTop;
      let percent = Math.floor(scrollTop / scrollHeight * 100);
      document.getElementById('percent').innerText = 'Percent : '+percent+'%';
    }
  </script>

Thanks Damien,

But this is not exactly what I wanted to achieve. I'll try to formulate better:

Giving a simple grid page with different images on it. I would like the scroll percentage of an image comparing to the current viewport. So when the image bottom is at the top of the viewport, it will be 0% and when the image top will be at the bottom of the viewport it will be 100%. The scroll percentage is relative to the image comparing to the viewport.

I already have these informations, just the formala is missing

var viewportHeight = $(window).height();
var viewportTopX = $(window).scrollTop();
var viewportBottomX = viewportTopX + viewportHeight;
var elementHeight = $elementContainer.outerHeight();
var elementTopX = $elementContainer.offset().top;
var elementBottomX = elementTopX + elementHeight;