Demoing and displaying JavaScript at the same time using CSS

Tuesday, May 8th, 2012 at 12:53 pm

When writing documentation or doing examples you constantly run into the same issue: how do you display and demo the code at the same time? You don’t want to have a code display and live code as they will get out of sync (on the other hand I always found that when copying code into a document I also cleaned it up and optimised it).

The easiest way for this are all the “new” services like JSFiddle, JSBin, Dabblet, Tinker.io and others (there seems to be a new one every month now) and you can even embed them into other documents, but it means you need an iframe and load content from another service (which might go down or get forgotten in the future).

The other way of course is to use Ajax/JavaScript to load the code into the page. Back in 2008, I wrote the Ajax Code Display script for that (and subsequently I never used it much).

I was wondering how you can simply demo and show inline JavaScript in a document without needing any extra libraries. The simplest way seemed to read out the innerHTML of the SCRIPT element and write it out into a PRE using textContent (innerHTML would render HTML or greater signs in the script, which isn’t the idea).

However, you can do a simple demo and display of the same script much easier these days using CSS. Check out this demo page for an upcoming Smashingmag article:

code displayed with CSS

If you do a view-source you find no other script in use, yet it displays in the page. What is this sourcery*? Simple, and it was Mathias Bynens who got me onto it: just display script elements as block and add some generated content to show the “Source” text:

script {
  display: block;
  white-space: pre;
  text-shadow:none;
  background: #333;
  color: #fff;
  font-family: monaco, courier, monospace;
  padding: 10px;
}
script::before{
  content: 'Source:';
  color: #0f0;
}

Mathias has much more detailed explanations on why that works but I for one am once again amazed just how much easier things are these days with the awesome browsers that we have.

* Sourcery = magical code that does (seemingly) unexpected things.

Tags: , , ,

Share on Twitter