Run This Script button for slides in Shower

NB: This is an old article (2017). Everything may have changed since publication.


I do my slides in Shower: it's easier to write in my usual editor, easy to publish and the result looks good by default.

Most of my presentations are about JavaScript and include bits of code in it, so I thought it would be nice to have a little "Run" button alongside each such snippet that would (you guessed it) run this code.

Code in Shower presentations is marked up as pre, and each line is wrapped in code, like this:

<section class="slide">
  <h2>Some code</h2>
  <pre>
    <code>function log() {</code>
    <code>  console.log('HELLO WORLD')</code>
    <code>}</code>
  </pre>
</section>

So here it goes. You just drop it in the end of your file (so it would pick up all pre tags). This snippet assumes that you have only JavaScript in your pres, but if that's not the case, just edit the first line to search by class (and mark with it your pre that do have JavaScript).

var pre = [].slice.call(document.querySelectorAll('pre'))
pre.forEach(p => {
  var txt = p.innerText
  var btn = document.createElement('button')
  btn.className = 'run-button'
  btn.innerText = 'Run'
  p.parentNode.insertBefore(btn, p)
  btn.onclick = () => {
    console.log('Running\n---\n' + txt + '\n---\nResult:')
    eval(txt)
  }
 })

And you also need to add some styles, that's why I add run-button class to the button.

This is one of these rare moments, where eval shines and is useful.

Published at by mt