killerprince182
killerprince182

Reputation: 465

Updating the mouse position while scrolling

I am trying to find the latest updated current mouse position relative to the whole document. I have set up a scroll event.

Since this event doesn't contain mouse location I have nested another event listener of mousemove inside this scroll event.

Even though, it works the problem I am facing is that if the user keeps the pointer in the same position and simply scrolls with the wheel, the latest position is not being updated unless I move the mouse.

What should I do? What can I use to detect the mouse position? I want simplest answer because I am learning css and js.

Here is my code:

document.addEventListener('scroll', (e) => {
  document.addEventListener('mousemove', (e1) => {
    total_scroll = window.scrollY + e1.clientY;
    console.log("Current Pos: " + total_scroll);
  })
})
body {
  height: 2000px;
}

Upvotes: 2

Views: 1977

Answers (1)

stann
stann

Reputation: 91

I think the best solution would be to separate these listeners, and keep updating some variable with current mouse position, and then, on scroll - just use the variable.

My previous answer was not proper, so I'll give another one:

<html lang="en">

<head>
  <title>Document</title>
  <style>
    body {
      height: 2000px;
    }
  </style>
</head>

<body>
  <script>
    let clientScrollY = 0;
    document.addEventListener('mousemove', (e1) => {
      clientScrollY = e1.clientY;
    })
    document.addEventListener('scroll', (e) => {
      total_scroll = window.scrollY + clientScrollY;
      console.log("Current Pos: " + total_scroll);
    })
    
  </script>
</body>

</html>

Also here is solution if you want to update onscroll and onmousemove.

<html lang="en">

<head>
  <title>Document</title>
  <style>
    body {
      height: 2000px;
    }
  </style>
</head>

<body>
  <script>
    let clientScrollY = 0;
    let totalScrollY = 0;
    
    function updateTotalScrollY(){
      totalScrollY = window.scrollY + clientScrollY;
      console.log(totalScrollY);
    }
    
    document.addEventListener('mousemove', (e1) => {
      clientScrollY = e1.clientY;
      updateTotalScrollY();
    })
    document.addEventListener('scroll', (e) => {
      updateTotalScrollY();
    })
  </script>
</body>

</html>

Upvotes: 2

Related Questions