The aim of these pages is to explain how to create a HTML rich content editor. The goal is to explain step by step how to build the editor. I'll try, as much as possible, to use VanillaJS (pure JS without external framework or libraries).
This first part explains how to create and focus the editor. Here is the result of this first part:
First, create a HTML div and add this attribute: contenteditable="true".
<div id="editor" contenteditable="true"><p>Edit here.</p></div>
We'll add some simple CSS on our editor:
#editor {
min-height:30vh;
max-height:80vh;
overflow-y:auto;
white-space: pre-wrap;
background-color: #eaeaff;
}
min-height:30vh specify the minimum height of our editor is 30% of the viewportmax-height:80vh specify the maximum height of our editor is 80% of the viewportoverflow-y:auto; allow the scrollbar if the content is heigher than the editoroverflow-y:auto; allow multiple consecutive spacesbackground-color: #eaeaff; for a better view of the editorWe'll also remove the margins on the <p> tag since this tag will be our paragraph
separator:
#editor p { margin: 0; }
First we get the editor node:
let editor = document.getElementById('editor');
Then we set the focus when the page is loaded:
document.addEventListener("DOMContentLoaded", function() {
editor.focus();
});
For debugging purpose, I added a new section for displaying the HTML content of the editor :
<pre id="output"></pre>
Everytime the content is changed, the output is updated:
let output = document.getElementById('output');
// Update the output when the editor is updated
document.onselectionchange = () => {
// Check if the editor is focussed
if (editor === document.activeElement)
{
output.textContent = editor.innerHTML;
}
}
Try to update the editor content to see the HTML output: