cursor_div wont follow the cursor when I scroll to the bottom

46 views Asked by At

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');`
2

There are 2 answers

0
imhvost On BEST ANSWER

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>

0
Ewan Reveille On

this code may correct the error :

  function updateCursor() {
  cursor.style.left = mouseX + 'px';
  cursor.style.top = mouseY + 'px';

  cursorBorder.style.left = mouseX + 'px';
  cursorBorder.style.top = mouseY + 'px';

  requestAnimationFrame(updateCursor);
}

updateCursor();

The use of classic Javascript can improve the performance, and may correct the error caused by jQuery ! I hope this helped you !