When the user finishes typing the URL into the contenteditable div, I want to auto-link it, for example Medium :)
.
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, , , .