I have a contenteditable div where I replace hashtags with clickable links when the user clicks on space or on enter. The user writes down:
I love but there is no fish at home|
He then realizes he made a mistake and then decides to go back and write
I love #sushi | but there is no fish at home
#sushi
gets replaced by:
<a href="https://google.com/sushi>#sushi</a>
Notice that the | shows the position of where I want the caret to be when the user presses spacebar. My current "placeCaretAtEnd" function places the caret at the end of the div and NOT behind the link that I just replaced sushi with. Is there a way to alter my current function to place the caret behind the link I just replaced in the text on the position shown above, so that the user can continue typing carelessly? So in raw html:
I love < a> #sushi< /a> | but there is no fish at home
/**
* Trigger when someone releases a key on the field where you can post remarks, posts or reactions
*/
$(document).on("keyup", ".post-input-field", function (event) {
// if the user has pressed the spacebar (32) or the enter key (13)
if (event.keyCode === 32 || event.keyCode === 13) {
let html = $(this).html();
html = html.replace(/(^|\s)(#\w+)/g, " <a href=#>$2</a>").replace("<br>", "");
$(this).html(html);
placeCaretAtEnd($(this)[0]);
}
});
/**
* Place the caret at the end of the textfield
* @param {object} el - the DOM element where the caret should be placed
*/
function placeCaretAtEnd(el) {
el.focus();
if (typeof window.getSelection != "undefined"
&& typeof document.createRange != "undefined") {
var range = document.createRange();
range.selectNodeContents(el);
range.collapse(false);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
} else if (typeof document.body.createTextRange != "undefined"){
var textRange = document.body.createTextRange();
textRange.moveToElementText(el);
textRange.collapse(false);
textRange.select();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div contenteditable="true" class="post-input-field">
I love (replace this with #sushi and type space) but there is no fish at home
</div>
function blueColor() { tweet = tweet.replace(/(^|\s)(#\w+)/g, " <a href=#>$2</a>").replace("<br>", ""); var savedSel = sel.saveCharacterRanges(this); sel.restoreCharacterRanges(this, savedSel); }
– Aran