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

65
Views
HTML element dragging ahead of cursor

So I have the main part of my dragging functionality implemented like this:

let dragSpeed = 1;
// called on mousemove event
function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();

    // Calculate new cursor position:
    newX = initialX - e.clientX;
    newY = initialY - e.clientY;
    initialX = e.clientX;
    initialY = e.clientY;

    const newLeftOffset = elmnt.offsetLeft - newX * dragSpeed;
    const newTopOffset = elmnt.offsetTop - newY * dragSpeed;

    if (newLeftOffset < boundaries.left.max && newLeftOffset > boundaries.left.min) {
      elmnt.style.left = newLeftOffset + "px";
    }
    if (newTopOffset < boundaries.top.max && newTopOffset > boundaries.top.min) {
      elmnt.style.top = newTopOffset + "px";
    }
  }

Now this works perfectly fine for any element I want to make draggable. The problem is that when I scale the parent element, it starts moving faster and ahead of the cursor when I drag it. I scale the parent element to emulate zooming in.

<body>
    <div id="container">
        <div id="myElement"></div>
    </div>
</body>
<script>
    // call drag function on #myElement
</script>
document.addEventListener("wheel", e => {
  const container = document.getElementById("container");
  // Zoom in
  if (e.deltaY < 0) {
    element.style.transform = `scale(${zoomLevel += 0.1})`;
  }
  // Zoom out
  else if (zoomLevel > 1) {
    element.style.transform = `scale(${zoomLevel -= 0.1})`;
  }
});

As far as I can see, #myElement is still moving the same amount of pixels regardless of the scale (the distance moved by the cursor), yet it moves ahead of the cursor when scaled. Am I misunderstanding something here? And is there a way to get it to move with the cursor when scaled?

about 4 years ago · Santiago Gelvez
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!