Search code examples
javascriptcursorcontenteditable

Set Cursor After an element


I have this code

elementSpan = document.createElement('span').className = 'mainSpan';
elementSpan.innerHTML = '<span class="childSpan">A</sapn>';
range.insertNode(elementSpan);
range.setStartAfter(elementSpan);  //the problem am having

Now I set the cursor to be after the elementSpan after inserting it into a contenteditable div but instead of the cursor to be after the elementSpan, it goes after the text A which is inside the <span class="childSpan"> but I want it to be after the elementSpan. Please anyone with a clue on how to do this?


Solution

  • Went through your question again, this is the closest I could get to work. This creates a dummy a with &nbsp; at the end and moves cursor past it. Both a and &nbsp; are important as without these some browsers (Safari, Chrome) force the text typed to go inside last element due to some optimisations. The code moves cursor to next element if there is one already, it can be removed by removing the if.

    I am not an expert in range/selection APIs. Looking forward to see other interesting answers.

    elementSpan = document.createElement('span');
    elementSpan.className = 'mainSpan';
    document.getElementById('ce').appendChild(elementSpan);
    elementSpan.innerHTML = '<span id="childSpan">Another text</span>'; //the problem am having
    setCursorAfterElement(document.getElementById('childSpan'));
    
    function setCursorAfterElement(ele) {
      if (!ele.nextElementSibling) {
        var dummyElement = document.createElement('a')
        dummyElement.appendChild(document.createTextNode('\u00A0'))
        ele.parentNode.appendChild(dummyElement)
      }
      var nextElement = ele.nextElementSibling
      nextElement.tabIndex=0
      nextElement.focus()
      var r = document.createRange();
      r.setStart(nextElement.childNodes[0], 1);
      r.setEnd(nextElement.childNodes[0], 1);
    
      var s = window.getSelection();
      s.removeAllRanges();
      s.addRange(r);
      //document.execCommand("delete", false, null);
    }
    #childSpan {
      border: 1px solid red;
      margin: 0px;
    }
    <div id="ce" contenteditable="true">
    </div>