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>
CodePudding user response:
Firefox adds <br>
on entering space, where as Chrome adds
.
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>