Question

I have a problem. I've been trying to tackle it for a while now and I'm ready to explode. Here's my requirement:
I have an external toolbar (not part of YUI) above the editor that I want to use to insert HTML tags. The user should be able to click a link on the toolbar after which a few things may happen:

  1. If there's any selected text, this text gets wrapped into an HTML tag
  2. If there's no selected text, an empty HTML tag is inserted in the editor
  3. Regardless of the scenario, cursor MUST be placed inside the new element, so that when the user enters more text, it resides in the new element

The functionality is very similar to that of pressing "B" or "U" buttons on the editor's toolbar (now that I'm using this editor, it also does it well :-)). It preserves everything nicely. So far I'm able to do 1 or 2, but not 3. Step 3 is VERY important, because without it, user experience greatly suffers. I really need your assistance to implement it. Below is a simplified version of the method that performs the insertion (just inserting DIV for the sake of simplicity). this._oEditor - local instance of 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 is it that I must do to place the cursor in the right position? Is it even possible? Also, if there's a better way of implementing this, I'm all for it. Thank you!

Was it helpful?

Solution

Here's complete the solution:

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(); 
}

OTHER TIPS

Placing the cursor requires different methods for different browsers. With IE you'll want to create a TextRange object, in Mozilla you can make use of window.find() or a Selection object, webkit/safari/chrome require yet another method.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top