Programmatically press "Left" key in a text input

Posted by Anurag on Stack Overflow See other posts from Stack Overflow or by Anurag
Published on 2010-05-14T03:35:29Z Indexed on 2010/05/14 3:44 UTC
Read the original article Hit count: 266

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".

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). Thanks for any help.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about javascript-events