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).
key 13 keycode is for ENTER key.
You can use: var e = jQuery. Event("keypress"); e. which = 13; //enter keycode e.
To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.
The keyup event occurs when a keyboard key is released. The keyup() method triggers the keyup event, or attaches a function to run when a keyup event occurs. Tip: Use the event.
e = jQuery.Event("keydown"); // define this once in global scope
e.which = 37; // Some key value
$("input").trigger(e);
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:
var keysPressed = new Array(); // somewhere in the global scope
$("input").keydown(function (e) {
keysPressed.push(e.which); //adding values to the end of array
});
Hope this helps
And for those not viewing jQuery as the solution to everything :)
From http://blog.josh420.com/archives/2007/10/setting-cursor-position-in-a-textbox-or-textarea-with-javascript.aspx
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);
if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
}
else
elem.focus();
}
}
}
As far as I can see, you can do:
var pos = document.getElementById("a").length;
document.getElementById("a").setSelectionRange(pos-1, pos-1);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With