<html-demo>
An element for displaying HTML content alongside its source code. Great for documenting web components!
<script>
tags (in code-first mode)From most to least likely to be implemented:
Code-first:
<html-demo>
<pre class="language-html"><code>
<input type=range>
</code></pre>
</html-demo>
Content-first:
<html-demo id=foo>
<input type=range>
</html-demo>
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%
).
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 |
---|---|
|
|
In code-first mode, any <script>
elements will also be executed:
<html-demo>
<pre class="language-html"><code>
<button>Click me</button>
<script>{
let button = document.currentScript.previousElementSibling;
// button.onclick = e =>
button.textContent = "Hi from script!";
}</script>
</code></pre>
</html-demo>
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:
document.currentScript
is null
in shadow treesdocument.querySelector*()
or document.getElementBy*()
calls will query the light DOMthis
will be the global window
object or undefined
in module scripts.<html-demo isolate>
<pre id="isolated-demo" class="language-html"><code>
<p>This demo has no actual content, but scroll down a bit 👇🏼 </p>
<script>{
let pre = document.getElementById("isolated-demo");
let container = pre.closest("body > *");
container.after("Hi from shadow tree script!");
}</script>
</code></pre>
</html-demo>
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 |
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.