Bugs with content editable
Lightweight Opensource Richcontent Editor
by Imabot
HTML
<h2>Editor</h2>
<div id="editor" contenteditable="true">Press enter just here 👇<span contenteditable='false'><b>contenteditable=false</b></span> </div>
<h2>HTML output</h2>
<pre id="output"></pre>
<small>More details on <a href="https://lucidar.me/en/rich-content-editor/non-editable-span-in-contenteditable/" target="_blank">my blog</a>.</small>
CSS
#editor {
min-height:30vh;
max-height:80vh;
overflow-y:auto;
/* white-space: pre-wrap; */
background-color: #eaeaff;
}
#editor p {
margin: 0;
}
.editor br {
display: none;
}
#output {
background-color: #ffeaea;
}
span[contenteditable=false] {
background-color:#faa;
}
JavaScript
document.execCommand('defaultParagraphSeparator', false, "p");
let editor = document.getElementById('editor');
let output = document.getElementById('output');
// Set focus to the editor when page is loaded
document.addEventListener("DOMContentLoaded", () => {
editor.focus();
});
// Update the output when the editor is updated
document.onselectionchange = () => {
// Check if the editor is focussed
if (editor === document.activeElement)
{
output.textContent = editor.innerHTML;
if (editor.getElementsByTagName("BR").length)
{
// Remove <br> tags
let html = editor.innerHTML;
html = html.replace('<br>', '');
editor.innerHTML = html;
}
}
}
editor.addEventListener("keydown", event => { output.textContent = editor.innerHTML; })
editor.addEventListener("keyup", event => { output.textContent = editor.innerHTML; })