CodePen’s Prefill Embeds are the perfect way to enhance documentation with live examples. With them, you keep all the code in your repo or blog post so you can easily update demos and track changes. To get started you can set everything up in a real Pen then copy out a Prefill Embed from the Embed Builder, or use the syntax to build your own!

Turning code samples into an interactive demo is cool enough, but you may not want that to happen right away. Let’s explore a way to turn code blocks into a CodePen Embed on click!

Here’s a sample copied directly from the Embed Builder.

<div class="codepen" data-height="265" data-theme-id="light" data-default-tab="html,result" data-user="codepen" data-slug-hash="fd63b769e68be117bc6dbc2d259d002c" data-prefill='{"tags":[],"scripts":[],"stylesheets":[]}'>
  <pre data-lang="html">&lt;h1>Hello from HTML&lt;/h1></pre>
  <pre data-lang="css">html {
  background: black;
  color: white;
  text-align: center;
}

h1::after {
  content: " / CSS!";
}
</pre>
  <pre data-lang="js">document.querySelector("h1").innerHTML += " / JavaScript";
</pre></div>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>

Adding Click to Run

The CodePen Embed script (ei.js) automatically turns elements with the codepen class into Embeds on page load. If we take off that codepen class so we can do a trick like this to make a Click to Run button:

<div data-height="265" data-theme-id="light" data-default-tab="html,result" data-user="codepen" data-slug-hash="fd63b769e68be117bc6dbc2d259d002c" data-prefill='{"tags":[],"scripts":[],"stylesheets":[]}'>
  ...
</div>
<script async src="https://static.codepen.io/assets/embed/ei.js"></script>
<script>
// Loop over all elements with the `data-prefill` attribute
Array.from(document.querySelectorAll('[data-prefill]'), ( el ) => {
  // Create a Click to Run button
  const button = document.createElement("button");
  button.innerHTML = "Click to Run";
  button.setAttribute("class", "prefill-click-to-run");
  el.appendChild(button);

  // On click, the element will become the embed!
  button.addEventListener("click", () => {
    el.classList.add("codepen"); // Add the codepen class back.
    window.__CPEmbed(); // Trigger the CodePen embed script to run again.
  });
});
</script>

Add a few styles and you can get some nice code blocks that turn into a Embed on click:

Syntax Highlighting, Lazy Loading, and More!

We can improve the setup even more with syntax highlighting through Prism.js, hidden code blocks, and a lazy load of the CodePen Embed script to keep your pages as light as possible!

All of these techniques put together gives you a lightweight, performant way to make on-demand Prefill Embeds for your docs or blog posts! Give it a whirl and share with us how you’re using Embeds.