Sunday, 29 May 2022

Contenteditable removes trailing whitespaces on firefox, but not on Chrome

I have simple <p> element as contenteditable with a formatting function, which formats the text on the fly (on input event), and moves the caret at the end of the text (because updating innerHTML on contenteditable moves the caret to the beginning of the text).

So on Chrome everything works fine, the text is formatted as you type, but when using Firefox, trailing whitespaces are removed as you type, so you can't really write two separate words, because each time you press space at the end of the first word, it gets trimmed.

Any ideas why the behaviour is different on Firefox?

Fiddle: https://jsfiddle.net/mt8cp2sd/

const content = document.getElementById('content');
content.innerHTML = 'Type text here';

function formatText(text) {
  return text.replaceAll('#', '<b>#</b>');
}

content.addEventListener('input', () => {
  content.innerHTML = formatText(content.innerText);

  let range = document.createRange();
  range.selectNodeContents(content);
  range.collapse(false);
  let selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
});
#content {
  border: solid 1px #555;
}
<html>

  <body>

    <p id="content" contenteditable>
    </p>

  </body>

</html>


from Contenteditable removes trailing whitespaces on firefox, but not on Chrome

No comments:

Post a Comment