Set the caret position always to end in contenteditable div

20,851

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

Share:
20,851
Mr_Green
Author by

Mr_Green

If you do not know or know - There won't be any conflicts If you pretend to know, there will be conflicts -- Shri Sadhguru Forget about your house of cards And I'll do mine Fall off the table And get swept under Denial, denial -- Radiohead - House of cards I'll paint it on the walls 'Cause I'm the one at fault I'll never fight again And this is how it ends -- Linkin Park - Breaking the habit

Updated on April 26, 2020

Comments

  • Mr_Green
    Mr_Green about 4 years

    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.