Search code examples
jqueryperformancemousemovemousedownmouseup

Mousemove gets slower when you move fast with mouse


im trying to make jquery box drag, but the problem is that when i drag really fast the "mousemove" is moving slower than my mouse and when the mouse gets out of the dragging #box the mousemove wont move, how can i fix this?:

function position(div,x,y) {

    x = x-100;
    y = y-100;

    $(div).css({'left':x, 'top':y});

}


$(document).ready(function() {

    var check = false;

    $("#box").mousedown(function() {

        check = true;

        $("#box").mousemove(function (e) {

            if(check != false) {

                position("#box", e.pageX, e.pageY);

            }

        });

    }).mouseup(function() {

        check = false;

    });

});

Solution

  • It's slowing down because you are using too many system resouces. So you need to find ways to reduce system usage.

    By delagating the mousemove to document, it runs a bit faster. It still lags a bit when you move the mouse really fast, but it's an improvement. Here's the code:

    $(document).ready(function() {
        var check = false,
            box = $("#box")[0];
    
        $(box).mousedown(function() {
            check = true;
        }).mouseup(function() {
            check = false;
        });
    
        $(document).mousemove(function(e) {
            if(check) {
                position(box, e.pageX, e.pageY);
            }   
        });
    });