<html-demo>

An element for displaying HTML content alongside its source code. Great for documenting web components!

Features

Roadmap

From most to least likely to be implemented:

Examples

Basic

Code-first:

<html-demo>
	<pre class="language-html"><code>
		&lt;input type=range>
	</code></pre>
</html-demo>

Content-first:

<html-demo id=foo>
	<input type=range>
</html-demo>

Adjusters

Only font-size for now:

<html-demo adjust="font-size">
	<button>Click me</button>
</html-demo>

Use --font-size-min and --font-size-max to set the range (default: 50% to 300%).

Style isolation

By default the demo is rendered in the light DOM, and thus inherits the normal page styles. In most cases, this is what you want. If not, you can use the isolate attribute to use the UA’s default styles. This works with both modes:

Content-first Code-first
<html-demo isolate>
	<button>Click me</button>
</html-demo>
<html-demo isolate>
	<pre class="language-html"><code>
		&lt;button>Click me&lt;/button>
	</code></pre>
</html-demo>

Execute script

In code-first mode, any <script> elements will also be executed:

<html-demo>
	<pre class="language-html"><code>
		&lt;button>Click me&lt;/button>
		&lt;script>{
			let button = document.currentScript.previousElementSibling;
			// button.onclick = e =>
			button.textContent = "Hi from script!";
		}&lt;/script>
	</code></pre>
</html-demo>

Executing scripts in isolated mode

Do note that there is limited utility in doing this in isolated mode, since there is no (easy) way to get a reference to any of the other elements in the demo:

<html-demo isolate>
	<pre id="isolated-demo" class="language-html"><code>
		&lt;p>This demo has no actual content, but scroll down a bit 👇🏼 &lt;/p>
		&lt;script>{
			let pre = document.getElementById("isolated-demo");
			let container = pre.closest("body > *");
			container.after("Hi from shadow tree script!");
		}&lt;/script>
	</code></pre>
</html-demo>

Auto-wrapping HTML code snippets on a whole page

The element class provides two helper methods for this very thing:

import HTMLDemoElement from "https://nudeui.com/html-demo/html-demo.js";

HTMLDemoElement.wrapAll({
	container: mySection,
	ignore: ".no-html-demo, #installation, #some-other-section",
});

All parameters are optional.

Name Default value Description
container document.body The element to search for <html-demo> elements.
ignore "" A CSS selector for elements to ignore.
languages ["html", "markup"] The language-xxx classes whose code snippets to wrap

Installation

Just include the component's JS file and you're good:

<script src="https://nudeui.com/html-demo/html-demo.js" type="module"></script>

In case you want to link to local files: CSS is fetched automatically, and assumed to be in the same directory as the JS file.