Build a Markdown Editor With Live Preview in Vanilla JS
Build a markdown editor with live preview in vanilla JavaScript: a textarea, a small parser, sanitized output, toolbar buttons and autosave to localStorage.

A markdown editor with a live preview is a satisfying small project. A text box on one side, rendered output on the other, and the output updates as you type. The interesting parts are not the textarea. They are turning markdown into HTML, doing it safely so pasted text cannot run scripts, keeping the interface responsive while the user types, and saving the draft. This post builds a markdown editor with live preview in vanilla JavaScript. It writes a small markdown converter for the common syntax so you can see how parsing works, then explains why for real documents you should use a maintained library with a sanitizer, and shows how to plug one in. It adds a toolbar that wraps the selected text, keyboard shortcuts, scroll syncing and autosave. Markdown syntax is described in the CommonMark specification.
The layout
Two panes side by side, a textarea for input and a div for output. The preview is a live region only if you want announcements, so leave it a plain region.
<main class="editor">
<section>
<label for="input">Markdown</label>
<div class="toolbar" role="toolbar" aria-label="Formatting">
<button type="button" data-wrap="**" title="Bold (Ctrl+B)">Bold</button>
<button type="button" data-wrap="*" title="Italic (Ctrl+I)">Italic</button>
<button type="button" data-wrap="`" title="Code">Code</button>
<button type="button" data-prefix="## " title="Heading">Heading</button>
<button type="button" data-prefix="- " title="List item">List</button>
</div>
<textarea id="input" rows="20" spellcheck="true"></textarea>
</section>
<section>
<h2 id="preview-title">Preview</h2>
<div id="preview" aria-labelledby="preview-title"></div>
</section>
</main>
<script type="module" src="editor.js"></script>.editor { display: grid; grid-template-columns: 1fr 1fr; gap: 1rem; padding: 1rem; }
textarea { width: 100%; box-sizing: border-box; font: 14px ui-monospace, monospace; }
#preview { border: 1px solid #ccc; padding: 0.5rem 1rem; overflow: auto; max-height: 28rem; }
@media (max-width: 700px) { .editor { grid-template-columns: 1fr; } }(a textarea on the left, a preview panel on the right, stacked on narrow screens)A tiny markdown converter
First, escape every piece of text so that raw HTML in the input is shown as text, not run. Then convert the supported syntax on top of the escaped text. The order matters: block rules first, then inline rules.
function escapeHtml(text) {
return text
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
}
function inline(text) {
return escapeHtml(text)
.replace(/`([^`]+)`/g, "<code>$1</code>")
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
.replace(/\*([^*]+)\*/g, "<em>$1</em>")
.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" rel="noopener">$1</a>');
}
export function toHtml(source) {
const lines = source.replace(/\r\n/g, "\n").split("\n");
const out = [];
let list = false;
let paragraph = [];
const flush = () => {
if (paragraph.length) out.push(`<p>${inline(paragraph.join(" "))}</p>`);
paragraph = [];
};
const closeList = () => {
if (list) out.push("</ul>");
list = false;
};
for (const line of lines) {
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
const item = /^[-*]\s+(.*)$/.exec(line);
if (heading) {
flush(); closeList();
out.push(`<h${heading[1].length}>${inline(heading[2])}</h${heading[1].length}>`);
} else if (item) {
flush();
if (!list) out.push("<ul>");
list = true;
out.push(`<li>${inline(item[1])}</li>`);
} else if (line.trim() === "") {
flush(); closeList();
} else {
closeList();
paragraph.push(line.trim());
}
}
flush(); closeList();
return out.join("\n");
}
console.log(toHtml("# Hi\n\nSome **bold** and `code`.\n\n- one\n- two"));<h1>Hi</h1>
<p>Some <strong>bold</strong> and <code>code</code>.</p>
<ul>
<li>one</li>
<li>two</li>
</ul>The link rule accepts only http and https addresses, which blocks javascript: links, a classic injection vector. Escaping first means a line such as <script>alert(1)</script> becomes visible text. This converter is deliberately small: no fenced code blocks, nested lists, tables, images or reference links. It is enough to learn from and too small to trust with arbitrary documents.
Wire the preview
Listen for input on the textarea and render. For a short document, rendering on every keystroke is fine. For long ones, batch the work in requestAnimationFrame so you render at most once per frame.
import { toHtml } from "./markdown.js";
import { save, load } from "./autosave.js";
const input = document.querySelector("#input");
const preview = document.querySelector("#preview");
let pending = false;
function update() {
pending = false;
preview.innerHTML = toHtml(input.value);
}
function schedule() {
if (pending) return;
pending = true;
requestAnimationFrame(update);
}
input.addEventListener("input", () => {
schedule();
save(input.value);
});
input.value = load() ?? "# Welcome\n\nStart typing **markdown** here.";
update();
console.log(preview.querySelector("h1").textContent);WelcomeSetting innerHTML is safe here only because every piece of text passed through escapeHtml. If you replace the converter with a library, sanitize its output.
Use a library for the real thing
A hand-written regex converter breaks on nesting, escaping and edge cases. For a real editor, use a library that implements CommonMark, such as marked or markdown-it, and sanitize the result with DOMPurify. Libraries are loaded as ES modules.
import { marked } from "https://cdn.jsdelivr.net/npm/[email protected]/lib/marked.esm.js";
import DOMPurify from "https://cdn.jsdelivr.net/npm/[email protected]/dist/purify.es.mjs";
export function toSafeHtml(source) {
const html = marked.parse(source, { gfm: true });
return DOMPurify.sanitize(html);
}
console.log(toSafeHtml("**hi** <img src=x onerror=alert(1)>"));<p><strong>hi</strong> <img src="x"></p>The sanitizer removed the onerror attribute but kept the harmless parts. Pin the version in the URL, as above, and in a build step prefer installing the packages. The sanitizing step is the one you must never skip, because markdown allows inline HTML by design, and a preview that renders unsanitized output is a cross-site scripting hole, particularly if the document can come from another person.
Toolbar and shortcuts
The toolbar wraps the selected text with a marker or adds a prefix to the line. Use setRangeText, which edits the textarea and keeps the undo stack working in most browsers.
function wrapSelection(marker) {
const { selectionStart: start, selectionEnd: end, value } = input;
const selected = value.slice(start, end) || "text";
input.setRangeText(`${marker}${selected}${marker}`, start, end, "select");
input.focus();
input.dispatchEvent(new Event("input"));
}
function prefixLine(prefix) {
const { selectionStart: start, value } = input;
const lineStart = value.lastIndexOf("\n", start - 1) + 1;
input.setRangeText(prefix, lineStart, lineStart, "end");
input.focus();
input.dispatchEvent(new Event("input"));
}
document.querySelector(".toolbar").addEventListener("click", (event) => {
const button = event.target.closest("button");
if (!button) return;
if (button.dataset.wrap) wrapSelection(button.dataset.wrap);
if (button.dataset.prefix) prefixLine(button.dataset.prefix);
});
input.addEventListener("keydown", (event) => {
if (!(event.ctrlKey || event.metaKey)) return;
if (event.key === "b") { event.preventDefault(); wrapSelection("**"); }
if (event.key === "i") { event.preventDefault(); wrapSelection("*"); }
});(select a word, press Ctrl+B, and it becomes **word** with the preview updated)Dispatching an input event after the programmatic change makes the preview and autosave react to it, because setRangeText does not fire one itself.
Autosave
Save the text in localStorage, throttled so each keystroke does not write. A short delay after the last change is enough.
const KEY = "markdown-draft";
let timer;
export function save(text) {
clearTimeout(timer);
timer = setTimeout(() => {
try {
localStorage.setItem(KEY, text);
} catch {
// storage unavailable
}
}, 400);
}
export function load() {
try {
return localStorage.getItem(KEY);
} catch {
return null;
}
}
save("Draft text");
setTimeout(() => console.log(load()), 500);Draft textThe read happens after the 400 millisecond delay, so it sees the saved text. On a fresh browser load() returns null, which is why the editor falls back to a welcome text with the ?? operator. Keep the name of the storage key unique to your page.
Practical notes
Sync the scroll positions of the two panes by mapping the textarea's scroll ratio to the preview, which is approximate but helpful. Keep the preview region from stealing focus. Add a count of words and characters, and confirm before discarding a draft. For accessibility, label both panes, keep the toolbar reachable by keyboard, and do not rely on color alone to distinguish elements. Finally, remember that large pasted documents can make per-keystroke rendering slow, so use requestAnimationFrame batching or a short debounce.
Syncing the two panes
A live preview feels connected when the two panes scroll together. The simple approach maps the textarea's scroll position to the preview as a ratio: divide scrollTop by the scrollable height, which is scrollHeight minus clientHeight, then apply the same ratio to the preview. It is not exact, because the rendered output has different line heights from the source, but it keeps roughly the same section in view, and for most documents that is enough.
function syncScroll() {
const max = input.scrollHeight - input.clientHeight;
const ratio = max > 0 ? input.scrollTop / max : 0;
preview.scrollTop = ratio * (preview.scrollHeight - preview.clientHeight);
}
input.addEventListener("scroll", syncScroll, { passive: true });
console.log(typeof syncScroll);functionIf you need exact alignment, have the converter record the source line number on each block, for example in a data-line attribute, and scroll the preview to the block that matches the first visible line. Libraries such as markdown-it make this practical through their token maps, which store the line range of each block.
Testing the editor
Test the converter with small inputs, one syntax at a time, and then with hostile input. Paste a line that contains a script tag, an image with an onerror attribute and a link with a javascript: address, and confirm that none of them can run. Test an empty document, a document with only blank lines and a very long line, and check that the list closes correctly when a paragraph follows it. For the interface, check that Ctrl+B wraps the selection, that Ctrl+Z undoes the toolbar change and that the draft is restored after a reload. Keep a small set of sample documents in your repository and compare the HTML your converter produces with the expected output, so a change to one rule cannot silently break another.
Keeping it fast on long documents
Rendering the whole document on every frame of typing is fine up to a few thousand words and wasteful after that. Two techniques help. The first is debouncing: wait 100 to 150 milliseconds after the last keystroke before rendering, which makes typing feel instant because the textarea is never blocked, and the preview catches up as soon as the person pauses. The second is skipping work that did not change, by comparing the new HTML string with the previous one and leaving the DOM alone when they are equal, since replacing innerHTML resets scroll positions, selections and any images already loaded in the preview.
For very large files, move conversion into a Web Worker, so parsing never competes with typing for the main thread. The worker receives the text and returns the HTML, and you ignore any response that is older than the latest request. That is the same stale-response problem a search box has, and the same fix of numbering requests solves it.


