Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

96
Views
React draggable element with no trailing lag

So what I'm trying to do is make a draggable div element that can be moved anywhere on a page, but for the life of me I can't seem to figure out why its 'losing grip' when you accelerate the mouse.

At first I wanted to use React DnD but I want to understand what is happening and why its not working.

The code basically boils down to this:

const callOverlayControlRef = useRef(null);

let offsetX;
let offsetY;

const handleUpdateElementPosition = (e) => {
    callOverlayControlRef.current.style.left = `${e.clientX - offsetX}px`;
    callOverlayControlRef.current.style.top = `${e.clientY - offsetY}px`;
};

const handleMoveOverlayControl = (e) => {
    offsetX = e.clientX - callOverlayControlRef.current?.getBoundingClientRect().left;
    offsetY = e.clientY - callOverlayControlRef.current?.getBoundingClientRect().top;

    callOverlayControlRef.current?.addEventListener('mousemove', handleUpdateElementPosition);
};

const handleClearHandlers = useCallback(() => {
    callOverlayControlRef.current?.removeEventListener('mousemove', handleUpdateElementPosition);
}, []);

return (
    <div ref={callOverlayControlRef}>
        <span
            onMouseDown={handleMoveOverlayControl}
            onMouseOut={handleClearHandlers}
            onBlur={handleClearHandlers}
        />
    </div>
)

So on mouse down on the span since of the div, I'm trying to move the div. It works well if you move the mouse slowly, but if you start to move faster if 'slipps away'.

Why is that happening? And what would be a better way of doing this?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!