Skip to content
Siddharth Blog
Go back

How to add live code previews to your website

When writing technical tutorials, providing a way for readers to interact with code snippets can improve the learning experience. Usually, this requires using heavy third-party embeds or setting up a backend to save and execute code.

A simpler approach is to use a stateless editor that handles code injection via URL parameters. This guide explains how to use the SE API to turn static code blocks into editable previews.

Overview of the SE API

The SE API is designed for technical bloggers who want to offer a “Try it Live” feature without the overhead of a database. It works by taking code from your existing page elements, encoding it, and passing it to a browser-based editor.

Because the editor is static and runs entirely in the client’s browser, it is fast and respects user privacy.

Implementation Steps

To set up live previews on your site, follow these steps.

1. Script Integration

First, include the API helper script in your HTML. This script identifies specific links on your page and handles the encoding logic.

<script src="https://editor.siddharth.at/api.js"></script>

2. Organizing Code Blocks

Place the HTML, CSS, or JavaScript you want to share inside elements with unique IDs. Using <pre> tags is recommended to ensure the code structure and indentation are preserved.

<pre id="my-html-code">
  <div class="box">Live Preview</div>
</pre>

<pre id="my-css-code">
  .box { background: #eee; padding: 20px; }
</pre>

To create a link that opens the editor, use an anchor tag with the class sideditor. Use the html, css, and js attributes to point to the IDs of the code blocks created in the previous step.

<a href="#" class="sideditor" html="my-html-code" css="my-css-code">
  Open in Editor
</a>

Considerations and Limits

Since this method uses the URL to pass data, there are a few technical constraints to keep in mind:

Conclusion

Using a URL-based injection method allows you to add interactivity to your articles with minimal configuration. It provides a functional environment for readers to test and modify code without leaving the context of the tutorial for too long.

For more technical details, you can refer to the API documentation.


Share this post on:

Next Post
CSS Media Queries Guide