2

I previously asked why setSelectionRange was't working and the answer was because it only works with input fields. But I would like to try to develop a spreadsheet type page using the contenteditable attribute.

window.onkeydown = function(e) {
 if (e.keyCode === 113) {
    setFocus()
 }
}


function setFocus() {
  element = document.getElementById('test')
  element.focus() // works
    .setSelectionRange(3,3) // Doesn't work
}
<div id="test" contenteditable>testing</div>
<p>Click in the Result window and then press F2.</p>

How can I place the cursor at the end of the field once the user presses F2?

SapuSeven
  • 1,473
  • 17
  • 30
Phillip Senn
  • 46,771
  • 90
  • 257
  • 373
  • You'll have to create a watcher for the event click. Then write an if where if the button is the unicode equivalent of F2 you will have to apply a css property. That's the description of more or less the direction you would have to go in. – rotato poti Aug 23 '18 at 21:31
  • Is there a way to press the End key for the user? – Phillip Senn Aug 23 '18 at 21:37
  • key simulation has changed a lot over the past few years. the code found on here about how to simulate an enter press works, even though you want a different key; the boilerplate is current. – dandavis Aug 23 '18 at 21:51
  • Try the answer here. I'm not sure what kind of element you are using. https://stackoverflow.com/questions/596481/is-it-possible-to-simulate-key-press-events-programmatically – rotato poti Aug 23 '18 at 21:55

1 Answers1

1

This could be a good solution for you:

window.onkeydown = function(e) {
 if (e.keyCode === 113) {
    setFocus()
 }
}


function setFocus() {
  element = document.getElementById('test')
  element.focus() // works
  setCaretPosition(element,1); // Also works
}

function setCaretPosition(el, pos) {
   
  el.focus();
  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(el, pos);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
}
<div id="test" contenteditable>testing</div>
<p>Click in the Result window and then press F2.</p>
Badis Merabet
  • 13,970
  • 9
  • 40
  • 55