YUI Editor (RTE): Paste the HTML element and place the cursor inside

I have a problem. I tried to do this for a while, and I'm ready to explode. Here is my requirement:
I have an external toolbar (not part of the YUI) above the editor that I want to use to insert HTML tags. The user should be able to click the link on the toolbar, after which several things can happen:

  • If there is selected text, this text will be transferred to the HTML tag
  • If there is no selected text, an empty empty HTML tag in the editor
  • Regardless of the scenario, the cursor MUST be placed inside the new element, so when the user enters more text, it is in the new element

The functionality is very similar to the functionality of pressing the "B" or "U" buttons on the editor toolbar (now, when I use this editor, it also works well :-)). He perfectly saves everything. So far I can do 1 or 2, but not 3. Step 3 is VERY important, because without it the user experience suffers a lot. I really need your help to implement it. The following is a simplified version of the method that performs the insertion (just pasting the DIV for simplicity). this._oEditor is a local instance of the YUI editor:

this._insertElement = function() {
var sSelection = this._oEditor._getSelection(); // Attempt to get selected text from the editor
if (sSelection == '') sSelection = ' '; // If nothing was selected, insert a non-breaking space

var sNewElt = '<div>' + sSelection + '</div>';

this._oEditor.execCommand('inserthtml', sNewElt);

this._oEditor.focus(); // This gives the editor focus, but places cursor in the beginning!
}

What should I do to put the cursor in the right position? Is it possible? Also, if there is a better way to implement this, I am all for it. Thanks!

+3
source share
2

:

this._insertElement = function() {
   var sSelection = this._oEditor._getSelection(); 
  if (sSelection == '') sSelection = ' '; 

  var sNewElt = '<div>' + sSelection + '</div>';

  this._oEditor.execCommand('inserthtml', sNewElt);

  var pos = 1000; //pos determines where to place the cursor. if greater than the length of characters, it will place at the end.
  if(this._oEditor.createTextRange) { //IE Specific code
        var range = this._oEditor.createTextRange();   
        range.move("character", pos);   
        range.select();   
    } else if(this._oEditor.selectionStart) {  //Works with Firefox and other browsers 

        this._oEditor.focus();   
        this._oEditor.setSelectionRange(pos, pos);   
  }  
  this._oEditor.focus(); 
}
+3

. IE TextRange, Mozilla window.find() Selection object, webkit/safari/chrome .

+1

Source: https://habr.com/ru/post/1707086/


All Articles