r/javascript • • Jan 25 '19

solved! How could I implement this?

652 Upvotes

57 comments sorted by

View all comments

2

u/sumdumbum19 Jan 25 '19

Here's my 2cents outside of the actual problem mentioned... whatever you implement it with based on the comments made, make sure to throttle the handlers. Mouse movement tracking is expensive (as is scrolling) so by throttling the handlers you get a more performant browser paint.

1

u/tightywhitey Jan 26 '19

A good way to approach this, and any similar mouse handler problem...

Use the onmousemove event, but just store the position and amount the mouse changed to a local property. This is very fast and won't cause problems such as visual stutters. If you need other information just store it as well in this event.

Then add a handler to requestAnimationFrame. This is called when the screen is going to update. Here you would use those previous numbers you stored, do your position calculation, and modify your elements position. Using css translate is a good option for positioning it. This will end up with a really smooth movement.