I am trying to programmatically fire a key event to go left in a text box, but not having any luck.
The input element has focus and the cursor is at the end. I’m trying to get the cursor to move left one step – before the letter “F” *programmatically by firing a Keyboard event (keydown/keyup/keypress) with the corresponding keystroke ← or → targeted at the input box.
ABCDEF|
Here’s the code so far:
HTML
<input id="a" type="text" />
Javascript
var keyEvent = document.createEvent("KeyboardEvent");
var keyLocation = '0x00';
var keyIdentifier = "Left";
keyEvent.initKeyboardEvent("keypress",
true,
true,
window,
keyIdentifier,
keyLocation,
false);
$("a").dispatchEvent(keyEvent);
Saved a quick demo on jsfiddle if you want to see the whole code – http://jsfiddle.net/Vsafv/
I am not interested in making this cross-browser (just get it working in Chrome).
where “input” is your textarea
37 – left
38 – up
39 – right
40 – down
So when you record your “events” you record the values for the keys pressed.
I’m sure you already figured out a way to do this but just in case, here’s an idea of how i would tackle it:
Hope this helps