Search code examples
javascriptcssmovesmoothing

How to handle glitch while moving div using position attributes via arrow keys?


Context:
I am trying to achieve smooth movement(top,left,bottom,right) of div using arrow keys.

Problem: enter image description here

The movement of div as you can see above is slightly glitchy, I have tried to use lodash throttle which seems like the correct approach to make it look smooth but it doesn't seem to solve the problem, not sure where am I going wrong, any suggestions would be helpful.

DemoRef -throttle vs debounce vs regular

Demo Ref 2

Code

   move: throttle(function (type) {
       if (type === "up") {
               this.moveUp(0);
       } else if (type === "down") {
               this.moveDown(0);
       } else if (type === "left") {
               this.moveLeft(0);
       } else if (type === "right") {
               this.moveRight(0);
     }
   }, 500),

What I have tried till now --> Codesandbox


Solution

  • This seems to be down to the your keyboard repeat rate. When you hold down a key it will fire, and then after a certain delay set in your OS it will then fire again and again. The delay between the first and second firing can be different from the delay between all the subsequent repeats. What you want to do is have the box animate smoothly across the screen, but if you add or subtract 10px to or from its position in response to the key firing you will get this kind of behaviour. I don't think that it will be easy to get a completely consistent movement because you need to make assumptions about the user's keyboard repeat rate. You could try adding a CSS transition to smooth it out, but it still might not give the best results.

    What I would suggest is to listen for keydown and keyup events, and add a loop (maybe using requestAnimationFrame to animate the div while the key is down. Once the key is lifted you halt the animation.