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

245
Views
JS: How to make a Div follow your cursors height

I am having problems trying to make this div have the same height on the screen as the cursor. Currently the div stays stationary. Here is what I have now:

  <body>
    <div id="container">

        <div id="mouseHover"></div>

    </div>

    <script>

        let box = document.getElementById('mouseHover');

        var mousex = 0;
        var mousey = 0;

        // Listens for where the mouse is hovering
        function mouse(){
        mousex = event.clientX;
        mousey = event.clientY;

        box.style.y = mousey;

        }

        document.addEventListener('mousemove', mouse);

    </script>
  </body>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

//Make the DIV draggagle:
dragElement(document.getElementById("mouseHover"));

function dragElement(elmnt) {
  var pos1 = 0,
    pos2 = 0,
    pos3 = 0,
    pos4 = 0;

  elmnt.onmousedown = dragMouseDown;

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
#container {
  width: 1700px;
  height: 100vh;
}

#mouseHover {
  width: 150px;
  height: 150px;
  border: 2px solid red;
}

.draggable {
  cursor: move;
  position: absolute;
  user-select: none;
}
<div id="container">

  <div id="mouseHover" class="draggable"></div>

</div>

I tried to reproduce your issue and made some changes to it. Below is the code. Hope that's how you wanted it to work.

Full working code at fiddle - https://jsfiddle.net/jkp15cyo/1/

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!