Search code examples
javascriptjavajqueryeventsmousedown

JS calculating distance mouse travelled on clicks


I am trying to calculate the distance that is recorded when the user clicks and stop the recording once the user has clicked again. How can i do this? As i am not very familiar with the mouse events I have tried using the click event but each time I click i stop the function altogether. I have the following code below.

var xTravelled = 0, yTravelled = 0, prevX, prevY, count = 0, select = false;
$(document).on({
    click : function(e) {
        select = true;
    },
    mousemove : function(e) {
        if (select) {
            prevY && (yTravelled += Math.abs(e.pageY - prevY));
            prevX && (xTravelled += Math.abs(e.pageX - prevX));

            prevX = e.pageX;
            prevY = e.pageY;

            $('#result').text(yTravelled + xTravelled);
        }
    }
});

Solution

  • Just change your

     click : function(e) {
            select = (select==false)?true:false;
    
        },
    

    here the fiddle