1

How can I simulate a keypress of the "right arrow" key to an input, using vanilla javascript?

I have an input and a button. I want the button to trigger a keydown for the "right arrow" key on the input.

 <input id="myInput" type="text">
 <button id="myButton>Click Me</button>

Basically, the end result should be :

  1. Click the button
  2. Cursor moves one place to the right (because we triggered a keydown press)

I have tried these solutions but they don't work:

Is it possible to simulate key press events programmatically?

https://elgervanboxtel.nl/site/blog/simulate-keydown-event-with-javascript

Bruno Crosier
  • 654
  • 9
  • 14
  • See this page for a working example of what you need to do. https://snipplr.com/view/5144/getset-cursor-in-html-textarea/ – Scott Marcus Aug 17 '18 at 00:02
  • @ScottMarcus you are right – Juan Aug 17 '18 at 00:04
  • If you click a button and initiate a right arrow key event, why do you expect the cursor move in some unrelated text input field as a result? Focus would be on the button element, so a key down on that element would probably attempt to scroll the page right (or something like that). If you're trying to initiate a key event, your links show you how to do that, but I wouldn't expect that to solve your cusor positioning problem straight away. If you're trying to move a cursor in a text box by button click, the key event isn't necessary. – ggorlen Aug 17 '18 at 00:17

1 Answers1

0

There's a handy blog post that gives you the full scoop on positioning a cursor in a text area. Here's a proof-of-concept version that may not work for older browsers (see link for a compatible version):

let cursorLocation = 0;

document.getElementById("myButton").addEventListener("click", e => {
  var input = document.getElementById('myInput');
  input.focus();
  input.setSelectionRange(++cursorLocation, cursorLocation);
});
<input id="myInput" type="text" value="sample text">
<button id="myButton">Click Me</button>
ggorlen
  • 44,755
  • 7
  • 76
  • 106