javascript - How to record timing for keypress event? -
i trying build small script shows, on call back, when press key q
after 1 second press w
should show q
, w
obviously, but when, press q
, w
not @ same time, in less 1 second, should show other single character ex: x
, stuck jsfiddle or full code.
<script type="text/javascript"> function check(e){ var text = e.keycode ? e.keycode : e.charcode; switch(text){ case 81: text = 'q'; break; case 87: text = 'w'; break; } if(text == 8){ var str = document.getelementbyid("out").innerhtml; var foo = str.substring(0, str.length -1); document.getelementbyid("out").innerhtml = foo; }else { document.getelementbyid("out").innerhtml += text; } } </script> <input type='text' onkeyup='check(event);' id='in' /> <div id='out' ></div>
i new javascript, , lost lets record 1 key press wait listen if there 1 existing inside second. have tried also, setinterval()
function, executes function amount of time given.
i think need:
var timer = new date(), previouschar; function check (e) { var foo, text = e.keycode ? e.keycode : e.charcode, out = document.getelementbyid('out'), str = out.innerhtml; switch (text) { case 81: text = 'q'; break; case 87: text = 'w'; break; } if (new date() - timer < 1000 && text === 'w' && previouschar === 'q') { text = 'x'; out.innerhtml = str.substring(0, str.length - 1); } if (text === 8) { foo = str.substring(0, str.length - 1); out.innerhtml = foo; } else { out.innerhtml += text; } previouschar = text; timer = new date(); return; }
a live demo @ jsfiddle.
edit
since you've added more requirements via comments, here's edited code task:
var timer = new date(), keycombinations = { ae: 'ä', oe: 'ö', qw: 'x' }; function check(e){ var text, str, previouskeys, key = e.keycode || e.charcode, out = document.getelementbyid('out'); text = string.fromcharcode(key); str = out.innerhtml + text; previouskeys = str.substring(str.length - 2, str.length); if (new date() - timer < 1000) { if (previouskeys in keycombinations) { str = str.substring(0, str.length - 2) + keycombinations[previouskeys]; } } out.innerhtml = str; timer = new date(); return; }
notice, code onkeypress
event. it's more reliable when creating characters keycodes. can assign separate eventhandling special keys, backspace, within onkeyup
handler function.
this not perfect code, gives idea, how implement task. uses object literal store key combinations , replacements. way don't need write loop @ all.
a live example @ jsfiddle.
Comments
Post a Comment