Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attemping to get a div to "follow" cursor on mousemove, but with a delay

I want to create the effect similar to the old mouse trails where the div is delayed but follows the cursor.

I have come reasonably close by using set interval to trigger an animation to the coordinates of the cursor.

$("body").mousemove(function (e) {
    if (enableHandler) {
        handleMouseMove(e);
        enableHandler = false;
    }
});

timer = window.setInterval(function(){
    enableHandler = true;
}, 250);

function handleMouseMove(e) {

  var x = e.pageX,
      y = e.pageY;

      $("#cube").animate({
        left: x,
        top: y
      }, 200);

}

JSFiddle

There are two problems that remain now:

  1. The 'chasing' div is very jumpy (because of the required use of set interval)

  2. If the mouse move stops before the animation is triggered, the div is left in place, away from the cursor.

like image 831
Cult Digital Avatar asked Nov 12 '15 15:11

Cult Digital


1 Answers

I did it slightly differently. Instead of using setInterval (or even setTimeout) - I just made the animation take x amount of milliseconds to complete. The longer the animation, the less responsive the following div will seem to be.

The only problem I notice is that it gets backed up if the mouse is moved a lot.

$(document).ready(function () {

    $("body").mousemove(function (e) {
        handleMouseMove(e);
    });

    function handleMouseMove(event) {

        var x = event.pageX;
        var y = event.pageY;

        $("#cube").animate({
            left: x,
            top: y
        }, 1);
    }
});

https://jsfiddle.net/jvmravoz/1/

like image 165
Mike Willis Avatar answered Oct 04 '22 22:10

Mike Willis