2

I have a requirement where i need to capture all the keys that a user has pressed and replay the same in the browser after a delay. E.g> if i have 3 text fields in a form, only field-1 will be enabled and focused on page load. Field-1 has a fousout event which will enable field-2, and field-3 after 10 seconds. Now user does the following without looking at the screen.

  1. User keys in "XYZ" in field-1.
  2. then immediately presses "TAB" key.
  3. keys in "123"
  4. presses "TAB" key
  5. keys in "XYZ123"
  6. presses "ENTER" key

all this is done in less than 10 seconds. i have done evt.preventDefault() for TAB and ENTER so that it does not submit the form nor tab away from the document. - How do i simulate the above keystrokes after 10 seconds?

I would want the results in the same order the user keyed in. i.e. - add values "123" to field-2 - most importantly invoke the browser TAB key functionality! - add then add values "XYZ123" to field-3 and so..on.

  • Is this achievable using javascript? e.g. Store all the keypress events and fire them one by one after 10 seconds?
  • If you have a log of which element the keypress occurred in and which keypresses took place you should be able to do this fine – dm03514 Aug 06 '15 at 19:50

2 Answers2

2

Admittedly I'm not sure if I completely understood your question, but this vanilla.js example will output what you've typed if you stop typing for one second:

'use strict';

var logged = [];
var timer;
var timeout = 1000;

document.body.addEventListener('keyup', function (event) {
  clearTimeout(timer);
  
  var character = String.fromCharCode(event.which);
  logged.push(character);
  
  timer = setTimeout(function () {
    document.body.innerHTML = logged.join('');
  }, timeout);
});
Start typing...

If nothing else, maybe it gives you an idea of how to solve your problem.

jdlm
  • 6,327
  • 5
  • 29
  • 49
  • but how do i simulate the tab event or Shift+tab events? Using the same example, i want the cursor to move to the next 'focusable' element after the 1 second timeout. in other words: invoke the browser default 'tab" functionality after 1 second. – user3329460 Aug 06 '15 at 21:40
  • 1
    It looks like i cannot simulate the native tab key events using custom scripts due to various security reasons. [fire-tab-keypress-event-in-javascript](http://stackoverflow.com/questions/1601593/fire-tab-keypress-event-in-javascript) – user3329460 Aug 06 '15 at 22:18
0

Perhaps this is what you are looking for :jQuery Key Press Event

You want to append the keystrokes to an array and then do whatever you want :)

Also this question may help How to find out what character key is pressed?

Community
  • 1
  • 1
Onilol
  • 1,315
  • 16
  • 41