How to Build a Live HTML Viewer with JavaScript (In Under 50 Lines)

Published on: by Dr. Talib

Have you ever wondered how tools like LiveHTMLViewer.com actually work? It might seem like magic, but the core concept is surprisingly simple. In this tutorial, we'll build a mini version of a live HTML editor using vanilla JavaScript.


The Core Concept

A live HTML viewer consists of two main parts:

  • The Input: A text area where you write code.
  • The Output: An <iframe> that renders that code.

The "magic" happens when we listen for typing events in the text area and immediately inject that text into the iframe's document.

Step 1: The HTML Structure

We need a simple layout with a textarea and an iframe.

<div class="container">
  <textarea id="code-input" placeholder="Type HTML here..."></textarea>
  <iframe id="preview-frame"></iframe>
</div>

Step 2: The CSS (Make it Look Good)

Let's use Flexbox to put them side-by-side.

.container {
  display: flex;
  height: 100vh;
}
textarea, iframe {
  width: 50%;
  height: 100%;
  border: none;
  padding: 1rem;
}
textarea {
  background: #1e1e1e;
  color: #fff;
  font-family: monospace;
}

Step 3: The JavaScript (The Magic)

Here is the script that connects them. We use the input event to detect changes.

const input = document.getElementById('code-input');
const preview = document.getElementById('preview-frame');

// Function to update the iframe
function updatePreview() {
  const code = input.value;
  preview.srcdoc = code;
}

// Listen for typing
input.addEventListener('input', updatePreview);

Why Use `srcdoc`?

The srcdoc attribute is a game-changer for this. It allows you to specify the HTML content of an iframe directly within the attribute itself, rather than needing a separate file URL. This is exactly what makes the update "instant."

Taking It Further

Our Live HTML Viewer takes this concept and adds powerful features like:

  • Syntax Highlighting: Using libraries like Ace Editor.
  • Code Formatting: Using JS-Beautify to clean up messy code.
  • Local Storage: Saving your work so you don't lose it if you close the tab.

Ready to code? You don't need to build your own tool to start practicing. Use our advanced editor right now to test your HTML skills!