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

107
Views
Div does not follow Mouse due to parent div

I have a problem where the mouse does not follow the div closely due to parent div left and top. Assume parent.jsx is developed by another developer, and I solely can control child.jsx, is there a way for me to make the div follow the mouse?

Here's the parent jsx

import "./styles.css";
import Child from "./child";


export default function Parent() {


  return (
    <div
      style={{
        top: "25px",
        left: "20px",
        position: "relative"
      }}
    >
      <Child />
    </div>
  );
}

The child jsx

import "./styles.css";
import { useRef } from "react";

export default function Child() {
  const descBox = useRef(null);
  const handleMove = (e) => {
    console.log(e.clientX, e.clientY);
    descBox.current.style.left = `${e.clientX}px`;
    descBox.current.style.top = `${e.clientY}px`;
  };
  return (
    <>
      <div
        onMouseMove={handleMove}
        style={{
          height: "300px",
          width: "100%",
          backgroundColor: "red"
        }}
      ></div>
      <div className="dropdown1" ref={descBox}>
        123asdfsfdafffasdfasfdsajkj
      </div>
    </>
  );
}

The css for child

.dropdown1 {
  position: absolute;
  left: 150px;
  top: 10px;
  background: #2b4557;
  padding: 4px 8px;
  font-size: 12px;
  line-height: 18px;
  color: #fff;
}

Codesandbox to run the code.

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

0

As the child is positioned absolute within the relative positioned parent you can work out its left and top positions relative to the parent and use those.

This code adds a small offset to give a slight gap between the cursor and the child (which you may or may not want).

const handleMove = (e) => {
  const rect = e.target.getBoundingClientRect();
  const x = e.clientX - rect.left + 10;
  const y = e.clientY - rect.top + 10;
  descBox.current.style.left = `${x}px`;
  descBox.current.style.top = `${y}px`;
};
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!