Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

266
Views
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>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Firefox adds <br> on entering space, where as Chrome adds &nbsp;.

You can set white-space css property of your contenteditable to -moz-pre-space to fix this.

Below is working code -

const content = document.getElementById('content');

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);
});

let data = '';
content.innerHTML = 'Type text here';
#content {
  border: solid 1px #555;
  white-space: -moz-pre-space;
}
<html>

<body>

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

</body>

</html>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!