Phillip Senn
Phillip Senn

Reputation: 47605

setSelectionRange works with input fields, but how can I place the cursor at the end of a contenteditable field?

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?

Upvotes: 2

Views: 571

Answers (1)

Bmaed Riasbet
Bmaed Riasbet

Reputation: 14998

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>

Upvotes: 1

Related Questions