Search code examples
javascriptjquerylistenerjquery-events

Capturing a single key input event Jquery


I'm listening to key and mouse input for 10 seconds, and "recording" the activity by pushing objects to an array that contain the time that the event occurred as well as mouseX and Y for mouse input, and which key was pressed. Eventually I want to run this 'history' back through some animation functions and 'replay' what the user entered.

A weird thing is happening, I will press a single key once, and expect at the end, keyCapture to be an array with one object. Instead, I'm getting like 100+ objects and I don't know why. Many of them are duplicates, even the time is identical.

function captureInput() {

mouseCapture = [];
keyCapture = [];

$(document).on('mousemove.capture', function(e) {
  var time = new Date().getTime();
  mouseCapture.push({
    x: e.pageX, 
    y: e.pageY,
    t: time
  });

  $(document).on('keyup.capture', function(e) {
    var time = new Date().getTime();
    keyCapture.push({
      key: e.which,
      t: time
    })
  });

});

setTimeout(function() {
  $(document).off('.capture');
  console.log(mouseCapture);
  console.log(keyCapture);
}, 10000);

}

How can I change my code so I'm only pushing one keyup object for every keyup event?


Solution

  • You are registering your keypress inside the mouse event (every time, over and over)! Move it outside that function call:

    function captureInput() {
    
        mouseCapture = [];
        keyCapture = [];
    
        $(document).on('mousemove.capture', function (e) {
            var time = new Date().getTime();
            mouseCapture.push({
                x: e.pageX,
                y: e.pageY,
                t: time
            });
    
        });
    
        $(document).on('keyup.capture', function (e) {
            var time = new Date().getTime();
            keyCapture.push({
                key: e.which,
                t: time
            })
        });
    
        setTimeout(function () {
            $(document).off('.capture');
            console.log(mouseCapture);
            console.log(keyCapture);
        }, 10000);
    
    }
    

    I formatted the code using the TidyUp button on JSFiddle.net. The problem becomes obvious when the indenting is correct :)