javascripthtmljquerycssmousemove

cursor_div wont follow the cursor when I scroll to the bottom


When Im at the top of the page. The curose_div will follow the cursor perfectly. But when I start scrolling to the bottom the cursor_div position will not follow correctly.

Heres my code

<div id="cursor"</div></div id="cursor_border"></div>

`var cursor = $('#cursor'); var cursor_border = $('#cursor_border');

$(document).mousemove(function(e){
    console.log(e.pageY + ' and '+ e.pageX ) ;

    
    var x = e.pageX;
    var y = e.pageY;
    cursor.css("left",x+'px');
    cursor.css("top",y+'px');
    
    cursor_border.css("left",x+'px');
    cursor_border.css("top",y+'px');`

Solution

  • Use event.clientX and event.clientY together with #cursor { position: fixed; }:

    window.onmousemove = event => cursor.style.transform = `translate3d(${event.clientX}px, ${event.clientY}px, 0)`;
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
    
    body {
      height: 200vh;
      background-image: linear-gradient(lightgreen, lightblue);
    }
    
    #cursor {
      position: fixed;
      width: 24px;
      height: 24px;
      display: none;
      margin: -12px 0 0 -12px;
      border: solid 2px red;
      border-radius: 50%;
      will-change: transform;
    }
    
    #cursor[style] {
      display: block;
    }
    <div id="cursor"></div>