Search code examples
javascriptjqueryscrollscrollmagic

What's the most accurate way of measuring scroll?


I'm making a slide scrolling page, and I'm trying to have it scroll like you're pulling a notecard up and with the next one right behind it.

To do this, I'm making them all fixed, and then moving their "top" position based off of scroll. But then I also need to make the body the size of the panel.

It's hard to describe what I'm doing, so here's the demo: https://codepen.io/NotDan/pen/vzraJE Here's the particular piece of code that's causing my problem:

//what's going on here?
$(window).scroll(function(){
  var panelNum = parseInt($(window).scrollTop()/$(window).height());//detemines panel number
  var pixelMovement = ($(window).scrollTop())-(panelNum*$(".panel").height()); determines how many pixels to move the panel by
  $('body').find(".panel:eq("+panelNum+")").css("top", -1*pixelMovement); 
});

The problem is when the user scrolls quickly, the top position is not set accurately and there's some overhang. Again, hard to explain, but if you jump to the demo and scroll quickly you'll see what I mean.

Is there a more precise way of measuring scroll? Or is there a better way to do what I'm trying to? I've tried scrollmagic, and its "section wipe" feature is really close, but they bring the previous one up rather than move the current one up.


Solution

  • I tried making a condition to determine the panel number and everything started working.

    var panelNum = 0;
    var pixelMovement = 0;
    $(window).scroll(function () {
        pixelMovement = $(window).scrollTop() - panelNum * $(".panel").height(); // determines how many pixels to move the panel by 
        $("body")
            .find(".panel:eq(" + panelNum + ")")
            .css("top", -1 * pixelMovement);
        if (Math.abs(pixelMovement) >= $(window).height()) {
            panelNum++;
        } else if (pixelMovement <= 0) {
            panelNum--;
        }
    });
    

    Here's the working demo: https://codepen.io/NotDan/pen/RYJeZq