How to move the cursor position within SCeditor?

193 views Asked by At

I am inserting text into an instance of SCeditor and would like to move the cursor after the insert, to a specific position within the inserted text.

Code of the SCeditor init:

var textarea = $('textarea[name="'+fieldname+'"]')[0];

// shortcut to insert custom text
sceditor.instance(textarea).addShortcut('ctrl+alt+b', function() 
{
   var fieldname = this.opts.id;
   parent.window['sce_'+fieldname].insertText('\\sqrt{}');
   
   // move cursor one to the left, so it is within the two brackets
   // ...
   
   return;
}

How to move the cursor?


Related Code I have found deals with the range object, but there was no example of how to move the cursor:

   var rangeHelper = this.getRangeHelper();
   var range = rangeHelper.selectedRange();
   rangeHelper.selectRange(range);
   range.setStartAfter(parent);
   rangeHelper.selectRange(range);
2

There are 2 answers

2
Sam On BEST ANSWER

Messing around with ranges is fairly horrible. The easiest way is probably to insert the text as HTML and include some special selection markers that SCEditor uses to restore selections. This should work:

// Remove any current markers
instance.getRangeHelper().removeMarkers()
// Insert the text with the special marker tags
instance.getRangeHelper().insertHTML(
    '\sqrt{' +
    '<span id="sceditor-start-marker" class="sceditor-selection sceditor-ignore" style="display: none; line-height: 0;"> </span>' +
    '<span id="sceditor-end-marker" class="sceditor-selection sceditor-ignore" style="display: none; line-height: 0;"> </span>' +
    '}'
);
// Focus will set the cursor to the markers
instance.focus()

When in source mode, it much easier (doesn't work in WYSIWYG mode, might be something it should do):

instance.insertText('\sqrt{', '}');
1
live627 On

You'll need to use Range.setStart() with a custom offset.

function setCaret() {
    var el = document.getElementById("editable")
    var range = document.createRange()
    var sel = window.getSelection()
    
    range.setStart(el.childNodes[2], 5)
    range.collapse(true)
    
    sel.removeAllRanges()
    sel.addRange(range)
}
<div id="editable" contenteditable="true">
  text text text<br>text text text<br>text text text<br>
</div>

<button id="button" onclick="setCaret()">focus</button>