Search code examples
javascriptkeypresscaretonkeydown

Prevent moving the caret when pressing arrow up key


I have an input field which has already an action to it, when pressing the arrow up key. But in Chrome, when you press the arrow key, it moves the carret to the left, and I don't want that

I was wondering if there is a way to get rid of the moving, and only do the action I want.

(In EDGE everything works fine)

Here is the action assigned:

    input.onkeydown = checkKey;
function checkKey(e) {
        e = e || input.event;
        if (e.keyCode == '38') {
            for ( var i = 0; i < split_command.length; i++ ){
            input.value += split_command[i];
            if ( i+1 < split_command.length ) input.value += " ";
            }
        }
    }

Ps. I'm making an online Command Prompt, and when I press the arrow up key, it inserts the last command into the input field.


Solution

  • I think what you are looking for is e.preventDefault();

    https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault