Search code examples
javascriptjquerywysiwygcontenteditable

Insert Using ExecCommand at Certain Point?


I'm currently making a WYSIWYG editor but having some problems. I'm trying to add links in but when I go to add a link it takes the focus away from the div as the user must type the link in a text box.

I've got a function that gets the last position of the cursor:

<div id="editor" contenteditable="true"></div>

function getCaretCharacterOffsetWithin(element) {
    var caretOffset = 0;
    var doc = element.ownerDocument || element.document;
    var win = doc.defaultView || doc.parentWindow;
    var sel;
    if (typeof win.getSelection != "undefined") {
        sel = win.getSelection();
        if (sel.rangeCount > 0) {
            var range = win.getSelection().getRangeAt(0);
            var preCaretRange = range.cloneRange();
            preCaretRange.selectNodeContents(element);
            preCaretRange.setEnd(range.endContainer, range.endOffset);
            caretOffset = preCaretRange.toString().length;
        }
    } else if ( (sel = doc.selection) && sel.type != "Control") {
        var textRange = sel.createRange();
        var preCaretTextRange = doc.body.createTextRange();
        preCaretTextRange.moveToElementText(element);
        preCaretTextRange.setEndPoint("EndToEnd", textRange);
        caretOffset = preCaretTextRange.text.length;
    }
    return caretOffset;
}

var update = function() {
  getCaretCharacterOffsetWithin(this);
};
$('#editor').on("mousedown mouseup keydown keyup", update);

Is there a way to ExecCommand at the caret point?

EDIT: Added a JSFiddle to see how things work - https://jsfiddle.net/hju3bLyx/2/


Solution

  • you need to save the selection when editor lost focus

    var savedSel;
    
    function createLink() {
      $('#editor').focus();
      var url = document.getElementById("url").value;
      restoreSelection(savedSel);
      document.execCommand("CreateLink", false, url);
    }
    
    // it saved here
    $('#editor').focusout(function(){
        savedSel = saveSelection();
    })