Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

268
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda