javascriptjquerysceditor

Setting the cursor to the end of the text using SCEditor


I am attempting to insert a quote, then move the cursor to the end of the editor. Currently, I insert the quote, the cursor ends up inside the quote so if you were to start typing, the user would be adding to the quote which is not what I would like to happen

I've tried looking through their documentation to figure out how to do this but I don't think I quote understand it

Here is my current code:

    $(document.body).on('click', '.action.quote', function() {

        var $target = $($(this).data('target'));
        var editor = $('#reply-body').sceditor('instance');
        var bodyText = $target.html();

        editor.insert('[quote=author]' + bodyText + '[/quote]');
        editor.focus();

        smoothScroll('#new-comment');
    });

Is there a quick way to do this? I'm quite new to SCEditor so it's all new to me


Solution

  • There currently isn't an easy way to place the cursor after inserted content although there probably should be. I'll create an issue to add one.

    For now you'll need to manually move the cursor using the range API. Something like this should work:

    $(document.body).on('click', '.action.quote', function() {
        var $target = $($(this).data('target'));
        var editor = $('#reply-body').sceditor('instance');
        var bodyText = 'Dummy text for example';
    
        editor.insert('[quote=author]' + bodyText + '[/quote]');
        editor.focus();
    
        var rangeHelper = editor.getRangeHelper();
        var range = rangeHelper.cloneSelected();
    
        // Handle DOM ranges, if you casre about IE < 9
        // you'll need to handle TextRanges too
        if ('selectNodeContents' in range) {
            var bodyChildren = editor.getBody()[0].children;
    
            // Select the last child of the body
            range.selectNodeContents(bodyChildren[bodyChildren.length - 1]);
    
            // Move cursor to after it
            range.collapse(false);
            rangeHelper.selectRange(range);
        }
    
        smoothScroll('#new-comment');
    });
    

    Live example: https://jsfiddle.net/3z8cg8z1/