I'm using Froala 2 and the documentation doesn't seem to have anything that implies a simple way to set the location of the caret, let alone at the beginning or end. I'm trying to seed the editor instance with a little content in certain cases and when I do using html.set, the caret just stays where it is at the beginning and I want to move it to the end. The internet doesn't seem to have anything helpful around this for v2.
            Asked
            
        
        
            Active
            
        
            Viewed 3,910 times
        
    5
            
            
        
        C. Augusto Proiete
        
- 24,684
 - 2
 - 63
 - 91
 
        webbower
        
- 756
 - 1
 - 7
 - 21
 
2 Answers
8
            Froala support provided an answer for me that works:
var editor = $('#edit').data('froala.editor');
editor.selection.setAtEnd(editor.$el.get(0));
editor.selection.restore();
        webbower
        
- 756
 - 1
 - 7
 - 21
 
- 
                    1This answer is correct, however the thing that tripped me up is the editor has to _already be focused_ for it to work. If you want to force focus on the editor before calling this call `editor.events.focus()`. – jpcamara Nov 03 '16 at 20:21
 - 
                    `editor.$el.get(0)` in this context did not always work as expected. What worked better for me was `editor.selection.endElement()`. – Pascal Lindelauf May 08 '19 at 13:11
 - 
                    My answer applied to some version of Froala 2. Maybe you're using a newer version where my answer doesn't work as well anymore? – webbower May 14 '19 at 18:58
 
1
            
            
        As far as I know, Froala 2 doesn't provide any API to do this, but you can use native JavaScript Selection API.
This code should do the job:
// Selects the contenteditable element. You may have to change the selector.
var element = document.querySelector("#froala-editor .fr-element");
// Selects the last and the deepest child of the element.
while (element.lastChild) {
  element = element.lastChild;
}
// Gets length of the element's content.
var textLength = element.textContent.length;
var range = document.createRange();
var selection = window.getSelection();
// Sets selection position to the end of the element.
range.setStart(element, textLength);
range.setEnd(element, textLength);
// Removes other selection ranges.
selection.removeAllRanges();
// Adds the range to the selection.
selection.addRange(range);
See also:
        Community
        
- 1
 - 1
 
        Michał Perłakowski
        
- 88,409
 - 26
 - 156
 - 177