1

I'm trying to simulate how the cursor moves in an input text field on left arrow key press in one of my tests, but it seems that the event doesn't work (maybe for security reasons?). Does anyone know a workaround?

Here a jsFiddle with an example: http://jsfiddle.net/UYW6M/.

$(function () {
    $('#check').click(function(e) {
        e.preventDefault();
        $('input').focus();
        console.log($('input')[0].selectionStart);
    });
    $('#move').click(function(e) {
        e.preventDefault();

        var press = jQuery.Event("keypress");
        press.ctrlKey = false;
        press.which = 37;
        $('input').focus();
        setTimeout(function(){
             $('input').trigger(press);  
             console.log('event triggered!');
        }, 1000);
    });
});

Key 37 is left arrow. Also doesn't work with other code (like 65 for inserting an "a").

I'm using jQuery here for simplicity, but my app is actually in Angular + Karma, in case someone knows a solution for that combo.

Jesús Carrera
  • 11,275
  • 4
  • 63
  • 55

1 Answers1

1

I think this is a security thing. But why do you need that? If you just want to change cursor position, then you even don't need jquery. Pure javascript:

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();
        }
    }
}

More information: Set keyboard caret position in html textbox

Community
  • 1
  • 1
Ihor Deyneka
  • 1,326
  • 1
  • 19
  • 37
  • I need that to check that when I hit the left arrow the cursor moves to the previous position within the string, instead of moving to another element as I have programmed to happen when the string is empty. If I change the cursor position programatically I'm not testing what happens when I hit the left arrow. – Jesús Carrera Jun 25 '14 at 06:25
  • If the cursor isn't currently in the input the `elem.selectionStart` or `elem.createTextRange` will be 0 so the if statements won't work, using `if(typeof elem.selectionStart !== 'undefined')` instead solves the issue – HastingsDirect Sep 27 '17 at 08:53