Search code examples
jqueryfocuscontenteditablecaretcursor-position

jquery Setting cursor position in contenteditable div


The old version of the question is below, after researching more, I decided to rephrase the question. The problem as before is, I need to focus a contenteditable div without highlighting the text, doing straight up focus highlights the text in Chrome.

I realize that people solved this problems in textareas by resetting the caret position in the textarea. How can I do that with a contenteditable element? All the plugins I've tried only works with textareas. Thanks.

Old Phrasing of the question:

I have a contenteditable element that I want to focus, but only insofar as to place the cursor at the front of the element, rather selecting everything.

elem.trigger('focus'); with jquery selects all the text in the entire element in chrome. Firefox behaves correctly, setting the caret at the front of the text. How can I get Chrome to behave the way I want, or is focus perhaps not what I'm looking for.

Thanks all.


Solution

  • demo: http://so.lucafilosofi.com/jquery-setting-cursor-position-in-contenteditable-div/

          <div id="editable" contentEditable="true">
                <h2>Lorem</h2> <p>ipsum dolor <i>sit</i> 
                   amet, consectetur <strong>adipiscing</strong> elit.</p> Aenean.
            </div>
    

        <script type="text/javascript">
            $(function () {
                $('[contentEditable="true"]').on('click', function (e) {
                    if (!$(this).hasClass('editing')) {
                        var html = $(this).html();
                        if (html.length) {
                            var range = rangy.createRange();
                            $(this).toggleClass('editing').html('<span class="content-editable-wrapper">' + html + '</span>');
                            var $last = $(this).find('.content-editable-wrapper');
                            range.setStartAfter($last[0]);
                            range.collapse(false);
                            rangy.getSelection().setSingleRange(range);
                        }
                    }
                }).on('blur', function () {
                    $(this).toggleClass('editing').find('.content-editable-wrapper').children().last().unwrap();
                });
            });
        </script>