Skip to content
Advertisement

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.

Advertisement

Answer

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/

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement