Mad-Chemist Mad-Chemist - 3 months ago 88
Javascript Question

Summernote - On focus, insert cursor at the end of editor

When the Summernote text editor initializes with the

property set to
, 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:


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

            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);
                return this;

Which originally came from this post: and then I modified to work with jQuery & specifically against Summernote.