scroll window when mouse moves
Asked Answered
M

1

7

Hello all

What I mean is while the mouse is moving towards the edge of the window (x or y or both), I want the page to scroll, and when the mouse stops moving, I want the page to stop scrolling.

There are numerous examples of how to scroll based on using a onClick event or a scroll zone at the edge of a window, but not much based on the movement of the mouse cursor.

Any help would be much appreciated.

Mariellemariellen answered 29/6, 2011 at 9:40 Comment(0)
H
6

Web pages are already designed to scroll using the scroll bar, page/home/end/arrow keys, etc. Is there any reason that's insufficient for your page? It's usually not a good idea to alter expected functionality.

You can read up on the mousemove event here. Anyway, the code below should work, but I really don't recommend using it. It can be especially disorienting for people with sensitive mice:

// Variables for current position
var x, y;

function handleMouse(e) {
  // Verify that x and y already have some value
  if (x && y) {
    // Scroll window by difference between current and previous positions
    window.scrollBy(e.clientX - x, e.clientY - y);
  }

  // Store current position
  x = e.clientX;
  y = e.clientY;
}

// Assign handleMouse to mouse movement events
document.onmousemove = handleMouse;
Hedgerow answered 29/6, 2011 at 10:13 Comment(2)
Perfect.. Thank you. Yes you are right changing the expected functionality isn't great but this page resembles a gallery wall so the feature of "look where you point" is a nice effect. To reduce "twitchyness" (and add some acceleration maybe), probably best I add some sort of easing effect. Is this possible?Mariellemariellen
Sure, you could just store var diffX = e.clientX - x in a variable and then check if (Math.abs(diffX) > 1) or something, you could divide it by 2 to make things less sensitive, etc. All you really need to know is that window.scrollBy will scroll the window by the supplied x and y parameters.Hedgerow

© 2022 - 2024 — McMap. All rights reserved.