Jump to content
Search Community

Scrolling an element horizontally based on mouse position

JulieAutobots test
Moderator Tag

Go to solution Solved by Rodrigo,

Recommended Posts

Hi! I'm about 90% of the way there with this piece of code. I'm trying to scroll an element left or right based off the proximity of the mouse to either edge of the screen. The closer to the edge of the screen the mouse is, the faster the element should scroll, and when it hits either edge of the element, it should stop. I've got it working by tying the scroll to a timeline, and using tl.timeScale() to slow down or speed up the animation based on the mouse's proximity to the edge. It works great when you're 'scrolling' to the right! But reversing the timeline and scrolling to the left is causing all sorts of jankiness and bouncing around when it reaches the edge of the element.

 

I'm sure I'm just making a simple error in how reversed timelines work, but I can't for the life of me figure out how to fix it. An extra set of eyeballs on this would be very appreciated!

See the Pen QWZxwPm by jbarkun (@jbarkun) on CodePen

Link to comment
Share on other sites

  • Solution

Hi,

 

I'd say that you're overcomplicating this a bit. This seems to work the way you expect:

$element.on("mousemove", function (e) {
  const mouseX = e.pageX;
  let strength;

  // If it gets within x distance from the left, animate the timeline backwards
  if (mouseX < distanceFromEdge) {
    strength = -(mouseX - distanceFromEdge);
    tl.timeScale(- (maxSpeed * (strength / distanceFromEdge)));
  }

  // If it gets within x distance from the right, animate the timeline forward
  if (mouseX > windowWidth - distanceFromEdge) {
    strength = -(windowWidth - distanceFromEdge - mouseX);
    tl.timeScale(maxSpeed * (strength / distanceFromEdge));
  }
});

Here is a fork of your codepen (thanks for the simple demo by the way, we love those around here :D)

See the Pen LYgrVQb by GreenSock (@GreenSock) on CodePen

 

Hopefully this helps.

Happy Tweening!

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...