Autolink URL in contenteditable

When the user finishes to type in a URL in a contenteditable div, I want to autolink it, like Medium does: http://d.pr/i/DsZH+).

I'm wondering how it is possible to achieve that using selection/range (I do not need to support IE, only modern versions of Chrome, Firefox and Safari), if possible without rangy (but if that is the only solution I would use it).

I'm able to detect if an URL preceed the caret after a user presses the space key, but I can't have execcommand('createLink'...) work on my range.

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

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

When I type a few characters and then a space, the 4 previous characters are not formatted in bold as I'd like, they just disappear from the div and only the new characters that I type afterwards are bolded.

Answers:

Answer

Finally found a workaround, without using execCommand:

  1. delete the range content: range.deleteContents()
  2. create the link node I want to insert
  3. insert the node in the range: range.insertNode(createdLinkNode)
  4. place the caret right after the inserted node:

 

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.