Search code examples
javascriptjqueryscrolldistanceparallax

Get amount of pixels scrolled from a div's height + its distance from the top


I'm looking for a way in jQuery or pure JS to get the amount of pixels scrolled, not from the top of the page, but from the bottom of a div.

In other words I need to turn the amount scrolled beyond a div's height + its pixel distance from the top of the page into a variable.

I want to append this parallax code below so instead of calculating from the top of the page, calculates from a target div's distance from the top + its height.

/* Parallax Once Threshold is Reached */

var triggerOne = $('#trigger-01').offset().top;     

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

  if ($(window).scrollTop() >= triggerOne) {

    function parallaxTriggerOne(){                                   
      var scrolled = $(window).scrollTop();
      $('#test').css('top',+(scrolled*0.2)+'px');
    }

    parallaxTriggerOne();

  } else {
    $('#test').css('top','initial');
  }  

});

I realize I didn't phrase this quite clear enough, I'm looking to only get the value of the amount of pixels scrolled since passing a div, so for example if I had a 200px tall div at the very top of the page and I scrolled 20 pixels beyond it, that variable I need would equal 20, not 220.


Solution

  • You can get a div's position by using div.offsetTop, adding div.offsetHeight into div's distance from top of page will give you bottom of div, then you can subtract from window's scroll to get your desired value.

    Feel free to ask if you have any doubts.

    var div = document.getElementById('foo');
    let div_bottom = div.offsetTop + div.offsetHeight;
    var doc = document.documentElement;
    var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
    var scroll_top, scroll_after_div;
    
    setInterval(function(){
      scroll_top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);
      scroll_after_div = scroll_top - div_bottom;
      console.log(scroll_after_div);
    }, 1000);
    body { margin: 0; }
    <div id="foo" style="position:relative; top: 100px; height: 30px; width: 100%; background-color: #000;"></div>
    
    <div id="bar" style="position:relative; top: 700px; height: 30px; width: 100%; background-color: #000;"></div>

    In this snippet setInterval method is printing the scroll value each second, you can scroll and see the change in value.