Search code examples
jqueryscrollcursormousemove

Follow mouse position with div (jQuery) - issue when scrolling


I've created a custom svg #cursor that follows my mouse position with jQuery (replacing the cursor using css limits the image size to 32px and looks pixelated on Retina, so I want to stick with using jQuery).

ISSUE: when the user scrolls, the cursor does not move which creates a jerky effect: https://jsfiddle.net/jhhbrook/ucuLefut/

I want my svg cursor to follow smoothly. How can I do this?

$(document).mousemove(function(e){
$("#cursor").css({left:e.pageX, top:e.pageY});

Solution

  • why not better use CSS cursor property itself?.As far as i know it's impossible to get cursor position without any mouse-event

     body {
     cursor:url(http://mayadufeu.github.io/img/cursor-auto.svg), auto;
     }
    

    https://jsfiddle.net/0chzmhrd/

    UPDATE:I think you can get mouse coordinates by using the code below but no clue how to animate the cursor nicely as the scroll event updates position in steps and not in continuous values.

    <html>
    <head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <style>
    body {cursor:none;}
    #content {height: 1200px;}
    #cursor {position: absolute;}
    #counter {position:fixed;margin:1px 0px 0px 100px;}
    </style>
    </head>
    <body>
    
    <p id="counter">counter</p>
    <img id="cursor" src="http://mayadufeu.github.io/img/cursor-auto.svg"/>
    <div id="content">
      content
    </div>
    
    </body>  
    <script type="text/javascript">
    var a;var b;
    $(document).ready(function(){
      $(document).mousemove(function(e){
          a = e.pageX;
          b = e.pageY;
      });
    
      $(document).mousemove(function(e){
        $("#cursor").css({left:e.pageX, top:e.pageY});
        $('#counter').text('Mouse -> X : '+a+ '  ' + 'Y: '+b);
      });
    
      $(document).scroll(function (e) { 
        $('#counter').text('Mouse -> X : '+a+ '  ' + 'Y: '+b);
        //can animate here
      });
    
    });
    </script>
    </html>
    

    Unfortunately doesn't run on JSfiddle idk why so try it out in a HTML file.