When the user finishes to type in a URL in a contenteditable div, I want to autolink it, like Medium does: ).
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.