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.
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.
The CaretPosition interface represents the caret position, an indicator for the text insertion point. You can get a CaretPosition using the Document. caretPositionFromPoint() method.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With