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

157
Views
Map to element position with pure css

Problem: I have an element that I need to drag with the mouse cursor. I've container element(for example 400x800) and I need to move my child element(2x2) when hovering over the container. I did it with React, but I've some performance issues. Please can you give me advice on how I can do it with Pure CSS without creating div elements for every px?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Drag’n’Drop algorithm

The basic Drag’n’Drop algorithm looks like this:

1. On mousedown – prepare the element for moving, if needed (maybe create a clone of it, add a class to it or whatever).
2. Then on mousemove move it by changing left/top with position:absolute.
3. On mouseup – perform all actions related to finishing the drag’n’drop.

Here’s the implementation of dragging a ball:

ball.onmousedown = function(event) {

let shiftX = event.clientX - ball.getBoundingClientRect().left;
  let shiftY = event.clientY - ball.getBoundingClientRect().top;

  ball.style.position = 'absolute';
  ball.style.zIndex = 1000;
  document.body.append(ball);

  moveAt(event.pageX, event.pageY);

  // moves the ball at (pageX, pageY) coordinates
  // taking initial shifts into account
  function moveAt(pageX, pageY) {
    ball.style.left = pageX - shiftX + 'px';
    ball.style.top = pageY - shiftY + 'px';
  }

  function onMouseMove(event) {
    moveAt(event.pageX, event.pageY);
  }

  // move the ball on mousemove
  document.addEventListener('mousemove', onMouseMove);

  // drop the ball, remove unneeded handlers
  ball.onmouseup = function() {
    document.removeEventListener('mousemove', onMouseMove);
    ball.onmouseup = null;
  };

};

ball.ondragstart = function() {
  return false;
};
about 4 years ago · Juan Pablo Isaza Report
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!