FriconiX
Free collection of beautiful vector icons for your web pages.

WYSIWYG rich content editor. Part 1. The basics

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:

Create the HTML editor

First, create a HTML div and add this attribute: contenteditable="true".

<div id="editor" contenteditable="true"><p>Edit here.</p></div>

Add some CSS

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

We'll also remove the margins on the <p> tag since this tag will be our paragraph separator:

#editor p { margin: 0; }

JavaScript

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

Debugging

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

Result

Try to update the editor content to see the HTML output:

See also


Last update : 03/23/2020