2

I have a contentEditable div which in some cases gets display: none, then again display: block (inline-block), I use div.focus() when display is set to block, but cursor is at the beggining of the text and I can't change its position to end on Chrome.

How can I make it to set cursor at the end, when the div gets focus?

pimvdb
  • 151,816
  • 78
  • 307
  • 352
John
  • 7,500
  • 16
  • 62
  • 95

1 Answers1

1

This uses jQuery but can be generalised to normal JavaScript. The important part is:

var range = document.createRange(),
    selection = window.getSelection();

range.setStartAfter(div.lastChild); // set cursor

selection.removeAllRanges();
selection.addRange(range); // apply cursor position

http://jsfiddle.net/te93D/1/

pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • This won't work in IE < 9 (in common with so many things), although it's unclear from the question whether this is a problem or not. – Tim Down Sep 07 '11 at 00:14