0

I have been working at inserting a string at the position of the cursor. I use a sample taken from here.
My problem is that the string to be added jumps to the end of the textarea. It does not stay at the position of the cursor. What could be the reason ? Could the problem comes from Mozilla Firefox ?

  function insertAtCursor(myField, myValue){
    //IE support
    if (document.selection) {
        myField.focus();
        sel = document.selection.createRange();
        sel.text = myValue;
    }
    // Microsoft Edge
    else if(window.navigator.userAgent.indexOf("Edge") > -1) {
      var startPos = myField.selectionStart; 
      var endPos = myField.selectionEnd; 

      myField.value = myField.innerHTML.substring(0, startPos)+ myValue 
             + myField.innerHTML.substring(endPos, myField.innerHTML.length); 

      var pos = startPos + myValue.length;
      myField.focus();
      myField.setSelectionRange(pos, pos);
    }
    //MOZILLA and others
    else if (myField.selectionStart || myField.selectionStart == '0') {
        var startPos = myField.selectionStart;
        var endPos = myField.selectionEnd;
        myField.value = myField.innerHTML.substring(0, startPos)
            + myValue
            + myField.innerHTML.substring(endPos, myField.innerHTML.length);
    } else {
        myField.innerHTML += myValue;
    }
}

here is the html part.

<button onclick="add_str()">
add srting
</button>
<script>
function add_str(){
    var elt = document.getElementById("text_write");
    insertAtCursor(elt, "ADD THIS VALUE");
}
</script>
<div contenteditable="true" id="text_write" style="height:200px; width:500px; border:2px solid black;"></div>


thank you in advance.

Kyv
  • 615
  • 6
  • 26

1 Answers1

2

I would just use setRangeText or execCommand

function add_str(event) {
  event.preventDefault()
  var elt = document.getElementById("text_write");
  insertAtCursor(elt, "ADD THIS VALUE");
}

function insertAtCursor(myField, myValue) {
  if (myField.setRangeText) {
    myField.setRangeText(myValue)
  } else {
    document.execCommand('insertText', false, myValue);
  }
}
<button onmousedown="add_str(event)">
add srting
</button>

<div contenteditable="true" id="text_write" style="height:200px; width:500px; border:2px solid black;">Hello World</div>
epascarello
  • 204,599
  • 20
  • 195
  • 236