We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Set cursor to end of text in RichTextEditor

I have a Rich Text Editor on my page. What is the best way to call a Javascript function to set the focus of the Rich Text Editor, and place the cursor at the end of the text?

1 Reply

PM Pandiyaraj Muniyandi Syncfusion Team December 17, 2019 12:30 PM UTC

Hi Brian, 
 
Greetings from Syncfusion support. 
 
We can set focus into RichTextEditor component by calling focusIn() public method with a component instance on the script section as follows 
 
 
<script> 
    document.getElementById('btnFocus').addEventListener('click', function () { 
 
        var rteObj = document.getElementById('defaultRTE').ej2_instances[0]; // Take component instance 
        rteObj.focusIn(); // Public method to set focus 
 
    }); 
</script> 
 
 
By executing following logic on external button click action, we can set a cursor position into the end of the text without calling a focusIn() method. 
 
 
<script> 
    document.getElementById('btnFocus').addEventListener('click', function () { 
        // To find last direct childnode 
        var editEleLastNode = document.querySelector('.e-richtexteditor .e-content').lastChild; 
 
        // Find the all text node from editor element 
        var textNodes = getTextNodesUnder(document, editEleLastNode); 
 
        // Last textnode, where we going to set a cursor 
        var lastTextNode = textNodes[textNodes.length - 1]; 
 
        var selectioncursor = new ej.richtexteditor.NodeSelection(); 
        var range = document.createRange(); 
        // to set the range 
        range.setStart(lastTextNode, 1); 
        // to set the cursor 
        selectioncursor.setRange(document, range); 
    }); 
 
    // Find the all text node from given node 
    function getTextNodesUnder(document, node) { 
        var nodes = []; 
        for (node = node.firstChild; node; node = node.nextSibling) { 
            if (node.nodeType === 3) { 
                nodes.push(node); 
            } 
            else { 
                nodes = nodes.concat(getTextNodesUnder(document, node)); 
            } 
        } 
        return nodes; 
    } 
</script> 
 
 
We have prepared sample for your reference, get it from below link 
 
In the above sample, we have done the following things 
 
  • On external button click action, we get the last direct child node of the editor element and it passed to getTextNodesUnder() method to find all text node elements.
  • The selection range created with the last text node element
  • Finally, range set and cursor placed at the end of the editor.
 
If you need any further assistance on this, kindly revert to us. 
 
Regards, 
Pandiyaraj 


Loader.
Live Chat Icon For mobile
Up arrow icon