Monday, 9 July 2018

Why the operation with click and spacebar is different from the cursor

I want to delete the written text and I want to save it and then insert it with a span
window.onload = function() {
  let written = '';

  document.getElementById('test').addEventListener('keyup', function(e) {
    console.log('IAM');
    var palabra = written;
    written += String.fromCharCode(e.which);

    if (e.which === 32) {
      var element = document.getElementById("test");
      var doc = element.ownerDocument || element.document;
      var win = doc.defaultView || doc.parentWindow;
      var sel = window.getSelection();

      sel.focusNode.textContent = sel.focusNode.textContent.replace(palabra, "");
      insertNodeAtCaret(document.createTextNode('INSERTED'));
    }
  })



}

function insertNodeAtCaret(node) {
  if (typeof window.getSelection != "undefined") {
    var sel = window.getSelection();

    var ht2 = document.createElement('span')
    ht2.innerHTML = node;
    if (sel.rangeCount) {
      var range = sel.getRangeAt(0);
      range.collapse(false);
      range.insertNode(ht2);
      range = range.cloneRange();
      range.selectNodeContents(ht2);
      range.collapse(false);
      range.innerHTML = 'hola';
      sel.removeAllRanges();
      sel.addRange(range);
    }
  }
}
<input type="button" onclick="insertNodeAtCaret(document.createTextNode('INSERTED'));" value="Insert node"
 onfocus="document.getElementById('test').focus()">

<div contenteditable="true" id="test">
  <span>Here</span> <span>is</span> <span>some</span> <span>editable</span> <span>text</span></div>
with click the text is placed exactly where the cursor is, instead with spacebar it's different, it inserts badly, I do not know why this difference happens, is it an event problem?
I want it to work with spacebar like the operation with click


from Why the operation with click and spacebar is different from the cursor

No comments:

Post a Comment