Code snippets and live previews

Something I've been wanting to build for a while: a way to show code and have a live preview as well. Of course I could use something like CodePen for this, but self-hosting, and self-building is the theme here.

<h1>Welcome</h1>
<p>This is my website, where I'm playing with code</p>

No need to worry about style, selectors, scope, containers, shadow DOM, and whatnot:

<style>
p {
	color: lime;
}
</style>

<p>Sweet!</p>

It should also work with interactive examples:

<button id="demo" hidden>Click me</button> <span></span>

<script type="module">
demo.addEventListener('click', function() {
	this.nextElementSibling.textContent = 'Works!';
});
demo.hidden = false;
</script>

This is using an <iframe> with a srcdoc attribute. Quite useful for this case.

You can play with all the code if you want, since it's using contenteditable="plaintext-only". Finally found a use case for it!

I still have to figure out how to make the color-scheme drip into the iframe nicely though. And I might add some more basic default styles at some point. Ow, and I'm not too happy with the tiny layout shift that happens on page load. But this is a nice start.

Onto more interactive blog posts!

Comments

Really, really cool! Also, TIL something!

Supervet! Heel bruikbaar in HTML presentaties :)

Very cool! I love the simplicity of the implementation.

Depending on personal preference, you could simplify further by expressing this.parentNode.nextElementSibling.setAttribute('srcdoc', '…'); as this.nextElementSibling.srcdoc = '…';

(We could even drop the this., but that might be more controversial.)

Add your comment

Making a reading progress indicator

Pseudo buttons