Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the caret position always to end in contenteditable div [duplicate]

In my project, I am trying to set the caret position always to the end of the text. I know this is default behaviour but when we add some text dynamically, then the caret position changes to starting point in Chrome and firefox (IE is fine, amazing).

Anyway to make it to work properly in chrome and firefox?

Here is the fiddle

<div id="result" contenteditable="true"></div>
<button class="click">click to add text</butto>

var result = $('#result');
$('.click').click(function () {
    var preHtml = result.html();
    result.html(preHtml + "hello");
    result.focus();
});

I tried adding setStart and setEnd as mentioned in this link but no use.

like image 784
Mr_Green Avatar asked Apr 26 '13 07:04

Mr_Green


People also ask

How do you set a caret cursor position in Contenteditable element div?

In order to set caret cursor position in content editable elements like div tag is carried over by JavaScript Range interface. The range is created using document. createRange() method.

What is caret position in JavaScript?

The CaretPosition interface represents the caret position, an indicator for the text insertion point. You can get a CaretPosition using the Document. caretPositionFromPoint() method.

How do I set the cursor position in input?

To move the cursor to the end of an input field: Use the setSelectionRange() method to set the current text selection position to the end of the input field. Call the focus() method on the input element. The focus method will move the cursor to the end of the input element's value.

How do you move a caret?

The simplest way to move the caret is to click the mouse at the desired location in the text area. The caret can also be moved using the keyboard. The LEFT , RIGHT , UP and DOWN keys move the caret in the respective direction, and the PAGE_UP and PAGE_DOWN keys move the caret up and down one screen-full, respectively.


1 Answers

I got the solution here thanks to Tim down :). The problem was that I was calling

placeCaretAtEnd($('#result'));

Instead of

placeCaretAtEnd(($('#result').get(0));

as mentioned by jwarzech in the comments.

Working Fiddle

like image 161
Mr_Green Avatar answered Nov 05 '22 08:11

Mr_Green