2

Afternoon,

I have a content editible div which, after appending some images too after uploaded, I wish to be focused the user can continue typing without having to click back into the div.

To my surprise,

.focus();

Works, but puts the curser at the start of the text, any way to put the curser at the end?

JSFiddle: http://jsfiddle.net/mxtasnbL/

Backup code:

<div class="textarea" contenteditable="true"></div>

var div = $(".textarea");
div.append('Some text before an image <br><img class="temp_added_image" src="http://www.deshow.net/d/file/car/2010-10/seat-electric-car-879-2.jpg"><br><br>');
div.focus();
Lovelock
  • 7,689
  • 19
  • 86
  • 186
  • 1
    Duplicate of: http://stackoverflow.com/questions/19568041/set-focus-and-cursor-to-end-of-text-input-field-string-w-jquery – Tyr Dec 27 '14 at 15:28

1 Answers1

2

One way is using a selection range that starts at where you want the caret to be:

var sel = window.getSelection(), range = sel.getRangeAt(0);
range.setStartBefore(div.children().last()[0]);
sel.removeAllRanges();
sel.addRange(range);

Updated fiddle: http://jsfiddle.net/techfoobar/mxtasnbL/2/

techfoobar
  • 65,616
  • 14
  • 114
  • 135