0

My cursor has a circular div that follows it using jQuery. I've noticed that when I scroll up or down the page, the circle stays where the cursor was until the cursor is moved again, and it catches up. Is there anything I can add to my code to make the circle stick to the cursor when scrolling?

I'd prefer to use jQuery if possible because I have absolutely no experience with pure JS.

JSFiddle - https://jsfiddle.net/7ynaj03L/1/

HTML

<span id="circle" class="circle"></span>

CSS

body, html {
    position: relative;
    height: 1000px; 
    width : 100%;  
    margin: 0;
}

.circle {
    position: absolute;
    background: #000000;
    opacity: .075;
    width: 40px; 
    height: 40px; 
    border-radius: 50%;  
    pointer-events: none;
}

jquery

jQuery(document).ready(function() {

  var mouseX = 0, mouseY = 0;
  var xp = 0, yp = 0;

  $(document).mousemove(function(e){
     mouseX = e.pageX - 20;
     mouseY = e.pageY - 20; 
  });

  setInterval(function(){
     xp += ((mouseX - xp)/3);
     yp += ((mouseY - yp)/3);
     $("#circle").css('transform', 'translate(' + xp + 'px, ' + yp + 'px)');
  }, 20);

});
Jack Averill
  • 821
  • 1
  • 10
  • 27
  • I think you are asking for something like this question's answer? https://stackoverflow.com/questions/53925568/how-to-make-custom-follow-cursor-follow-y-axis-scroll – RukshanJS Mar 22 '21 at 14:30
  • Hi stackerRook, yes that's similar, but I'm looking for a way to do this with jQuery if possible so I don't have to completely scrap what I've already made. I'm also completely inexperienced with pure JS. – Jack Averill Mar 22 '21 at 14:33
  • Does this answer your question? [Get mouse position on scroll](https://stackoverflow.com/questions/6519043/get-mouse-position-on-scroll) – freedomn-m Mar 22 '21 at 14:34
  • Hi, I had a look at the answers and I'm not really sure how that could help my `#circle` div stick to the cursor on scroll – Jack Averill Mar 22 '21 at 14:44
  • Because your circle is positioned based on the mouse position and you want it to be updated when you scroll - so you need to get the mouse position on scroll. – freedomn-m Mar 22 '21 at 16:02

1 Answers1

0

Use position: fixed; instead of position: absolute;.

Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Hi, sorry I just signed in after months being inactive on here and saw this. Fixed positioning doesn't work unfortunately, I tried already. The circle doesn't follow the cursor when scrolling. – Jack Averill May 09 '23 at 13:06