How to Build a Rich Text Editor: A Step-by-Step Guide

Building a rich text editor from scratch gives you complete control over formatting features like bold, italic, lists, and headings. Rather than relying on third-party libraries, you can leverage the browser’s built-in contentEditable attribute and document.execCommand API. This tutorial walks you through the core steps to create a functional rich text editor that you can customize further.

First, set up a basic HTML structure: a toolbar div with buttons for formatting commands, and a content area (a div with contentEditable="true"). Each toolbar button should trigger a JavaScript function that calls document.execCommand(command, false, value). Common commands include 'bold', 'italic', 'underline', 'insertUnorderedList', and 'formatBlock' for headings.

Article illustration

1. Enable Content Editing

Create a <div id="editor" contenteditable="true"></div> element. This allows users to type and format text directly. Add basic CSS to give it a white background, a border, and a minimum height. For example: min-height: 200px; border: 1px solid #ccc; padding: 10px;. This simple setup turns a plain div into an editable region.

2. Build the Toolbar

Create toolbar buttons using <button> elements. Attach onclick event handlers that call JavaScript functions. For instance:

  • Bold: onclick="document.execCommand('bold')"
  • Italic: onclick="document.execCommand('italic')"
  • Heading: onclick="document.execCommand('formatBlock', false, 'h3')"

Use <i> tags or text labels to indicate the action. Keep the toolbar inline with CSS display: flex or inline-block buttons.

3. Handle Active State and Styling

To visually indicate when a formatting command is active (e.g., bold button highlighted), listen for the input or mouseup event on the editor. Use document.queryCommandState('bold') to check if the current selection is bold. Toggle a CSS class like .active on the corresponding button using JavaScript.

4. Save and Restore Content

To persist the editor content, use the innerHTML property of the editor div. Save it to localStorage or send it via AJAX. For example: localStorage.setItem('editorContent', editor.innerHTML). On page load, restore it: editor.innerHTML = localStorage.getItem('editorContent') || ''. Always sanitize the HTML if you plan to display it elsewhere to prevent XSS attacks.

Conclusion

You now have a basic rich text editor using native browser APIs. Extend it by adding a font size dropdown, link insertion, or image upload. Remember that document.execCommand is deprecated but still widely supported. For modern projects, consider the contentEditable + Selection API approach for more control. Start small, test cross-browser, and gradually add features.

sarah antaboga
Author: sarah antaboga

Leave a Reply

Your email address will not be published. Required fields are marked *