javascripthtmlselectioncontenteditable

contentEditable - how to force to write after tag, not inside


I have div with contentEditable and when I add an element into it via JS, like: <span>text</span> I am not able to move cursor after - so when user input something it is going into the span. Is there any way how to prevent that?

<p class="line">Some text <span>text</span>[write_here]</p>

I want to force it to write into [write_here] position.

Here is an example, when you just add element and write it is going into the span - red. You are not able to write out of it after.

const input = document.querySelector('div.content');
const result = document.querySelector('div.result');
const addBtn = document.querySelector('button.addbtn');

input.addEventListener('input', () => {
  result.innerText = input.outerHTML;
});

const createElement = (content) => {
  const element = document.createElement('span');

  element.classList.add('mention');
  element.innerText = `@${content}`;

  return element;
};


addBtn.addEventListener('mousedown', () => {
  const element = createElement('test');
  
  const selection = window.getSelection();
  const selectedRange = selection.getRangeAt(0);
  
  selectedRange.deleteContents();
  selectedRange.insertNode(element);
  
  selectedRange.setStart(element, element.length);
  selectedRange.collapse(true);

  selection.removeAllRanges();
  selection.addRange(selectedRange);
  
  // How to properly move cursor after the `span` to write outside of the span. Even solve when user writes something and delete text right next to the end of the span. 
});
.content {
  width: 350px;
  height: 20px;
  background: lightblue;
}

span.mention {
  background: red;
}
<div class="content" contentEditable="true"><br/></div>
<button class="addbtn">Add element</button>
HTML:
<div class="result"></div>


Solution

  • I have solved it by adding zero width no break space \uFEFF after the element:

    https://www.compart.com/en/unicode/U+FEFF