Here I am


Simple web demos with livedemo

11 Mar 2014

livedemo.js is a small script I wrote to make writing HTML, CSS and JavaScript demos easier. It takes the text out of highlighted <code> snippets and adds elements and CSS to the DOM and executes JS code.

I initially wrote it for this blog post and I use it on

Use it

  1. Add a comment that contains the text enable javascript as the first, unindented line in code that you want to demo.

  2. Highlight code in your HTML page with something like redcarpet or Pygments (both available in Jekyll) or Prism.

  3. Download and include the script somewhere in your HTML page: <script src="livedemo.min.js"></script> (after Prisim if you're using it).


Code elements matching the HTMLSelector and whose first textNode's textContent match the HTMLFlag RegExp will be demo'd.

<!-- enable javascript to view a demo -->
<svg id="demo-svg" viewBox="0 -50 400 100">
    <polygon points="80 -40, 120 40, 40 40" fill="#29e" />
    <rect height="80" width="80" y="-40" x="160" fill="#4e4" />
    <circle cx="320" cy="0" r="40" fill="#f40" />

<!-- enable javascript to view a demo --> will be noticed by livedemo. The comment is removed and the remaining content is inserted into the document beside the code element's parent's parent by default.

If for example the HTML on the page is

        <code class="language-html">
            ... the generated highlighted code ...

then the textContent of the <code> will be inserted after the </div> within a new element.

This makes it convenient for Jekyll sites using redcarpet or Pygments.


The text of code elements that match the CSSSelector and have firstChildren that match the CSSFlag RegExp will be added to document.head in <script> tags.

/* enable javascript to vew demo */
#demo-svg {
    width: 100%;
    height: 25%;


Elements that match the JSSelector and whose firstChild's textContent matches the JSFlag RegExp will have their text executed.

// please enable javascript
var demoSvg = document.getElementById('demo-svg');

demoSvg.addEventListener('click', function (event) {
    alert('click on <' + + '>');

The script above will be executed and the flag comment will be removed form the <code> block.

JavaScript code is executed after HTML and CSS is inserted into the document. If the execution of a code block throws an error, the element and error are logged to the console.


The properties of the object window.liveDemoSettings are used to change settings for livedemo if they are set before the DOMContentLoaded event occurs and calls window.liveDemo. The properties are: