Ben Poon
Ben Poon

Reputation: 125

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?

Upvotes: 1

Views: 104

Answers (2)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

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 :)

Upvotes: 4

Spokey
Spokey

Reputation: 10994

I noticed this with a syntax highlighter

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

  // }); should end here 

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

}); // ends

Your problem seems to be that every time you move the mouse you'll keep on creating listen events so by the time you press a key all of those will run resulting in a lot of objects

Upvotes: 2

Related Questions