Autolink URL in contenteditable

When the user finishes typing the URL into the contenteditable div, I want to auto-link it, for example Medium :) http://d.pr/i/DsZH+.

I am wondering how this can be achieved with a selection / range (I do not need to support IE, only modern versions of Chrome, Firefox and Safari), if it is possible without rangy (but if this is the only solution I would use it).

I can find that the URL precedes the carriage after the user presses the space bar, but I cannot work execcommand('createLink'...)in my range.

Here is a very simplified example ( jsfiddle ), where I try to format in bold 4 characters preceding the carriage after the user presses the space bar:

$("#editor").on("keypress", function(event) {
  var pressedChar = String.fromCharCode(event.which);
  if(/\s/.test(pressedChar)) {
    var selection   = window.getSelection();
    var range       = selection.getRangeAt(0);
    range.setStart(range.startContainer, range.startOffset - 4);

    selection.removeAllRanges();
    selection.addRange(range);
    document.execCommand('bold', false);
  }
}

, , 4 , , div, , , .

+1
1

, , execCommand:

  • : range.deleteContents()
  • node
  • node : range.insertNode(createdLinkNode)
  • node:

 

range.setStartAfter(createdLinkNode);
range.setEndAfter(createdLinkNode);
selection.removeAllRanges();
selection.addRange(range);
+2

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


All Articles