prasad prasad - 13 days ago 5
HTML Question

DIV contentEditable Link formatting: How to prevent the append when typing at the time of input?

I was match url link and replace

a
tag with clickable link type using some regex expression.Its work perfect .After the matched text apply with in input .Text will typing with wrong place.And also the all text will appended.

See the below snippet:

please type something inside the div they will append.please help How to prevent the append & cursor always with end of the text.



function testinf(that){
var some="";
some =that.innerHTML.replace(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/g, function(match){
return '<a href="'+match+'" target="_blank">'+match+'</a>';
});
that.innerHTML=that.innerHTML;
that.innerHTML=some;

console.log(some)
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div oninput="testinf(this)" contentEditable="true">sone http://www.some.com type</div>




Answer

When you replace the text, you have to use textContent as below instead of innerHTML. Also, I have given below a cross browser method to move the cursor to the end.

function testinf(that){
  var some = "";
  some = that.textContent.replace(/(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\w@?^=%&amp;\/~+#-])?/g, function(match){
  return '<a href="'+match+'" target="_blank">'+match+'</a>';
});
  //that.innerHTML=that.innerHTML;
  that.innerHTML = some;
  placeCaretAtEnd(that);

console.log(some)
}

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://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div oninput="testinf(this)" contentEditable="true">sone http://www.some.com type</div>