4

When the Summernote text editor initializes with the focus property set to true, the editor gains focus but places the cursor at the beginning of the editor.

My preference would be to have the cursor placed where the user had clicked initially. At a bare minimum I would just need to place the cursor at the end of the editor.

The Summernote API doesn't seem to directly support this and I've tried various hacky looking solutions; Such as emptying the text area, creating the editor, then inserting the HTML nodes. The cursor remains at the beginning of the line still.

Forgot to include my fiddle: http://jsfiddle.net/madChemist/gvy3po4L/1/

Mad-Chemist
  • 487
  • 6
  • 18

1 Answers1

6

Here is the solution I've modified to work for me:

$.fn.extend({
    placeCursorAtEnd: function() {
        // Places the cursor at the end of a contenteditable container (should also work for textarea / input)
        if (this.length === 0) {
            throw new Error("Cannot manipulate an element if there is no element!");
        }
        var el = this[0];
        var range = document.createRange();
        var sel = window.getSelection();
        var childLength = el.childNodes.length;
        if (childLength > 0) {
            var lastNode = el.childNodes[childLength - 1];
            var lastNodeChildren = lastNode.childNodes.length;
            range.setStart(lastNode, lastNodeChildren);
            range.collapse(true);
            sel.removeAllRanges();
            sel.addRange(range);
        }
        return this;
    }
});

Which originally came from this post: https://stackoverflow.com/a/6249440/2921200 and then I modified to work with jQuery & specifically against Summernote.

Mahdi Bashirpour
  • 17,147
  • 12
  • 117
  • 144
Mad-Chemist
  • 487
  • 6
  • 18
  • This code should be called after jQuery has been initialized. EX: $('#FieldToFocus').placeCursorAtEnd(); – Mad-Chemist Aug 13 '16 at 22:00
  • I tried doing that in my [example here](http://stackoverflow.com/q/39396888/4896260) and I wasn't able to get it working. Can you help me @Mad-Chemist on where it should be placed? – usr4896260 Sep 09 '16 at 11:44
  • @usr4896260 Check out my response to your ticket here: http://stackoverflow.com/a/39706123/2921200 – Mad-Chemist Sep 26 '16 at 14:58
  • @Mad-Chemist, where I need to add this code also how can I call that function? – Bhaumik Pandhi Jun 06 '17 at 17:24
  • Add the above code within jQuery's $(document).ready callback if possible. You want the above code to execute as soon as jQuery is initialized. Once that happens, you are free to call the method at your leisure "$('#FieldToFocus').placeCursorAtEnd();" but swap out the jQuery selector in the example. – Mad-Chemist Jun 07 '17 at 21:18
  • The answer is missing what element to call this on: `$("#your-summernote-element").closest(".note-editing-area").find('[contenteditable]').placeCursorAtEnd();` – Skeets Sep 23 '19 at 05:35