Ryan Gavin Ryan Gavin - 1 year ago 270
jQuery Question

JavaScript or jquery trigger left arrow key press event (Simulate arrow key press)

I am trying to simulate the left and the right arrow key press in a text area within a rad grid control (Telerik).

I have a bug that is specific to the browser Firefox where the tab event(got this part fixed) and the arrow keys wont work. Every other browser works fine.

So as a workaround i want to simulate the arrow keys using JavaScript or jquery.

Below is what i have working with the tab event fix included. In addition to this I check if the key code 37 (this is the left arrow key) is pressed. At this point i want to simulate the left arrow press in the text area.

$(document).on('keydown', function (event) {
if (event.keyCode == 9) { //tab pressed
event.preventDefault(); // stops default action

$('body').keyup(function (e) {

var code = e.keyCode || e.which;

//Left arrow key press
if (code == '37')
moveLeft();// This does not trigger the left arrow event

//Tab button pressed
if (code == '9') {
//shift was down when tab was pressed focus -1
if (e.shiftKey && code == 9) {
var focused = $(':focus');
var inputs = $(focused).closest('form').find(':input');
inputs.eq(inputs.index(focused) - 1).focus();
//tab was pressed focus +1
else {
var focused = $(':focus');
var inputs = $(focused).closest('form').find(':input');
inputs.eq(inputs.index(focused) + 1).focus();

Any help on this issue would be appreciated


I got this working by moving the cursor back one space, below is the code I used to simulate the left arrow key press. I

$('body').keydown(function (e) {

     var code = e.keyCode || e.which; //Find the key pressed

     if (code == '37') {

          e.preventDefault(); // stop default action
          var elementId = e.target.id;// get id of input text area                                     

          var el = document.getElementById(elementId),
          myval = 1 // set mouse cursor to move back one space
          cur_pos = 0;

          if (el.selectionStart) {
              cur_pos = el.selectionStart;
          else if (document.selection) {

              var r = document.selection.createRange();
              if (r != null) {
                  var re = el.createTextRange(),
                  rc = re.duplicate();
                  rc.setEndPoint('EndToStart', re);

                  cur_pos = rc.text.length;

          if (el.setSelectionRange) {
              el.setSelectionRange(cur_pos - myval, cur_pos - myval);
          else if (el.createTextRange) {
              var range = el.createTextRange();
              range.moveEnd('character', cur_pos - myval);
              range.moveStart('character', cur_pos - myval);