How to determine how much user will scroll by pixels when user start scrolling using mouse wheel in Javascript

Viewed 1174

How to determine what amount of pixels will be moved by vertical scroll bar when user start to scroll using mouse wheel in javascript

I have a situation where user's scroll will result change in offsetTop between 200px to 1000px that I like to know ahead of time, do we have any way to figure out this situation using javascript?

5 Answers

If I understand your question correctly, the short answer is 'no'. To illustrate this, consider the following equivalent question:

I have detected a keydown event on the down arrow. Can I predict when the user will release the down key?

This is not possible. It is up to the user when they release the key and you have no way of anticipating when this will be.

Regarding mouse wheel events specifically, you'd also need to consider hardware / mouse and software / browser variations, which is going to make an (already impossible?) task even more difficult.

An alternative approach: Debounce your mouse-wheel events

Without more information about your overall objective it is difficult to know whether this will help, but you can use a debounce function to normalise a mouse-wheel event across a period of time. So whether the user scrolls for (say) 0.5s or 1s, you will only get one event, which should simplify any calculations you need to do.

Here is a basic Javascript Stackblitz example, debouncing a mousewheel event to every 0.1s. If you do a continuous mouse-wheel scroll, only the first event should be emitted.

RxJS has a debounceTime function built in. I'm not familiar with React so I can't advise exactly how this would be applied to mouse events, but the principle would be the same as the example above.

I understood that you wanted to get the pixels are going to be scrolled when a scroll event starts.

But this is not a just a web/code issue. The scroll keeps on ongoing until the user feels to stop.

This also depends on the mouse Wheel hardware . There are mouses with hard wheels which stop exactly when we release our fingers & other mouses which having soft gears, continues the scroll motion a bit longer (Newton's Law of Motion).

Web developers has no control over these hardwares upcoming performances(predictive performances) such as when will the user release his finger from a particular key or when will the user release the mouse button etc...

Only thing which we get is the hardware's completed/ongoing performances(Finished tasks/current) such as keyup , keydown,click , scrolling

These events returns what is happening as of now & what happened just before


Only way to predict what could be the expecting scroll duration is by Machine Learning ,by understanding how usually the user scrolls , understanding about the scrolling device they use etc..

But why do we need it? The use case which i could come up with this is a ML model for understanding user's scroll behaviour

I have a situation where user's scroll will result change in offsetTop between 200px to 1000px that I like to know ahead of time, do we have any way to figure out this situation using javascript?

For this particular scenario , there is no use case of getting the scrolling pixels before it stops.A basic scrolled event is more than enough.

Maybe you want this to give a mini animation before reaching 1000px , which can be done directly using css & javascript by creating a eventlistener on scroll (if current offsetTop==1000px then .... )

This is a snippet , which tells you how much pixel the user have scrolled in a scroll event(Completed task)

const ph=document.documentElement.scrollHeight;
console.log(ph)
document.querySelector('.rem').innerHTML="you have scrolled "+window.pageYOffset+". Scroll ends after "+((ph-window.innerHeight)-window.pageYOffset);
document.onscroll = () =>{
if(window.pageYOffset>1000){
 var cl=document.getElementById("gm");
 cl.classList.add("wow");
}
if(window.pageYOffset<1000){
 var cl=document.getElementById("gm");
 cl.classList.remove("wow");
}
document.querySelector('.rem').innerHTML="you have scrolled "+window.pageYOffset+". Scroll ends after "+((ph-window.innerHeight)-window.pageYOffset);
};
.rem{
position:fixed;
top:0;
}
.demo{
height:5000px;
}

.wow{
background:#FFCB2B;
transition:2s;
}
<span class="rem" id="xy"></span>
<div class="demo" id="gm">
<div>

Well yes , i will create a simple machine learning JS snippet for this scrolling event by first studying the user's scrolling behaviour

I am only training for a unidirectional scroll as of now.So for each scroll ,do either upscroll or downscroll

First 10 scrolls , will be only for Learning . Later onwards , when you start a scroll event , it will predict the upcoming scroll value with the learned values

The model will be learning continuously , as it won't stop after learning for first 10 tries. Higher the the learn value , more realistic prediction value u get

const ph=document.documentElement.scrollHeight;
const sp=[];
var prevscroll=0;
var curscroll=0;
learn=0;
var scrollTimer = -1;
console.log(ph)
document.querySelector('.rem').innerHTML="you have scrolled "+window.pageYOffset+". Scroll ends after "+((ph-window.innerHeight)-window.pageYOffset);

document.onscroll = () =>{

if (scrollTimer != -1)
       clearTimeout(scrollTimer);
  scrollTimer = window.setTimeout("scrollFinished()", 300);
if(learn>=10){
var c=avgscroll()
document.querySelector('.rem').innerHTML="your expected scroll pixels are "+c;
}

};
function avgscroll(){
  curavg=0
sp.forEach((item, index)=>{
      if(index!=0)
        curavg=(curavg+item)/(2)
       else
          curavg=item
});
return curavg;
}
function scrollFinished() {
        learn=learn+1;
        curpoint=window.pageYOffset
        curscroll=Math.abs(window.pageYOffset-prevscroll);
        prevscroll=curpoint;
        sp[learn]=curscroll
        console.log("Current Scroll was "+ curscroll)
        if(learn<=10)
        document.querySelector('.rem').innerHTML="Current Scrolled pixels were "+curscroll+" learning "+ learn + " of 10";
        
    }
.rem{
position:fixed;
top:0;
}
.demo{
height:50000px;
}
<span class="rem" id="xy"></span>
<div class="demo">
<div>

@Dip Parmar, I'm giving you both, the previous scroll position and the current scroll position in a separate useDocumentScroll.js file. Previous scroll is the end point of one scroll which ur looking for. I have done it in React functional hooks. You can make use of them accordingly as required in the RequiredPage.js by putting your own logic. I have also included some logic.. isScrolledDown & isMinimumScrolled for you. I could not exactly get what you wanted to make using it. My code for ur question is as below:

useDocumentScroll.js

import { useEffect, useState } from "react";


function useDocumentScroll(callback) {
  const [, setScrollPosition] = useState(0);
  let previousScrollTop = 0;

  function handleDocumentScroll() {
    const { scrollTop: currentScrollTop } =
      document.documentElement || document.body;

    setScrollPosition(previousPosition => {
      previousScrollTop = previousPosition;
      return currentScrollTop;
    });

    callback({ previousScrollTop, currentScrollTop });
  }

   useEffect(() => {
    window.addEventListener("scroll", handleDocumentScroll);

    return () =>
      window.removeEventListener("scroll", handleDocumentScroll);// eslint-disable-next-line
  }, []);
}

export default useDocumentScroll;

RequiredPage.js

import React from "react";    
import useDocumentScroll from "./useDocumentScroll";

export default function RequiredPage() {
const MINIMUM_SCROLL = 80;

useDocumentScroll(callbackData => {
const { previousScrollTop, currentScrollTop } = callbackData;
const isScrolledDown = previousScrollTop < currentScrollTop;
const isMinimumScrolled = currentScrollTop > MINIMUM_SCROLL;
});

return (
     <div>
     <h1>Some Text or Add some Lorem Ipsum </h1>
     </div>
       );
    }

I read your comment 'I am trying to make footer fixed which is inside iframe but it should be adjusting it's position based on parent window scroll..' based on what you said i tried to make something which will suit your requirement.

See this in fullscreen

var block=document.getElementById('div');
    
window.addEventListener('scroll',function(){
var scrolled=window.scrollY;
   
if(scrolled>=471 && scrolled<=963){
    block.style.overflowY="scroll";
    
    
    if(block.scrollTop>=519){
        block.style.overflowY="hidden";
    
    }
    else if(block.scrollTop>=0){
        
    block.scrollTop+=(scrolled-519);
    window.scrollTo(0,scrolled);
    
}


}
else{
    if(scrolled<=741){
    block.style.overflowY="scroll";
   
    block.scrollTop=0;
    if(block.scrollTop<=0){
        block.style.overflowY="hidden";
    }
}

    window.scrollTo(0,scrolled);
}
});
*{
            margin: 0px;
            padding:0px;
        
        }
        body{
            height:2400px;
        }
        p{
            font-size: 20px;
        }
        #div{
           position: absolute;
           scroll-behavior: smooth;
           height:401px; 
           width: 97vw;
           margin-top:570px;
           background-color:black;
           color: white; 
           padding:10px;
           z-index: 14;
        }
        #div::-webkit-scrollbar {
  display: none;
}
        #p_3{
            position: absolute;
            margin-top:940px;
            background-color: white;
            color: black;
            z-index: 11;
            width: 100vw;
            padding: 10px;
            
        }
        #p_1{
            position: absolute;
            background-color: white;
            color: black;
            z-index: 11;
            width: 100vw;
            padding: 10px;
            
        }
<div id="p_1">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>
<div id="div">
    <div id="p">
    <p >1 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color:red; color:white">2 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: #FF5733; color:white">3 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color:#FCB607; color:white">4 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color:#FCDB07 ; color:white">5 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: yellow; color:white">6 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: #07D7FC; color:white">7 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: #07B2FC; color:white">8 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: #0755FC; color:white">9 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p style="background-color: black; color:white">10 Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>

</div>
</div>
<br>
<br>
<br>
<div id="p_3">
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p >Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p >Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

But if you still want to stick to mouseWheel then you should go after IntersectionObserver.

The “Intersection Observer” provides a way to asynchronously observe changes in the intersection (overlapping) of elements. This can be in relation to other elements, or the viewport.

What i guess from your query you want this kind of solution

window.addEventListener("scroll", (event) => {
    let scroll = this.scrollY;
    console.log(scroll)
});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body style="height:900px;background-color:limegreen;">
  
</body>
</html>

Related