Less maintenance code tutorials with Ajax Code Display
Date : 2008 01 28 Category : Tech & DevelopmentOne of my main annoyances with writing code tutorials is that you need to maintain code in several locations: the code itself and the examples in the tutorial document. This is not really a problem when you can use a scripting language or print out the tutorials from a CMS, but when you just want people to get an HTML document you're in trouble. As I am right now writing a lot of articles I didn't want to waste my time and thought about using Ajax to load the code I am documenting into the HTML on the fly. The result looks something like this:
All you need to do is to add jQuery, the script and a class of "codeexample" to a link in the document you want to display. The script creates a PRE element with the code inside, replaces all the special characters, tabs with spaces and adds line numbers. For example:
PLAIN TEXT HTML:<p><a href="ordered.html" class="codeexample">ordered.html</a></p>
If you only want to show certain lines (which you'll have to do if you want to explain some code step-by-step) you can define the lines as a list including ranges. Say you want to display line 5, 10 and 12 to 21, then you'd add:
PLAIN TEXT HTML:<p><a href="ordered.html" class="codeexample lines[5,10,12-21]">ordered.html</a></p>
You can highlight lines of code in the same manner, say you want like 18 to 20 in bold:
PLAIN TEXT HTML:<p><a href="ordered.html" class="codeexample lines[5,10,12-21] highlight[18-20]">ordered.html</a></p>
Last but not least you can make the link clickable to show an IFRAME with the rendered output. Clicking the link again will remove the iframe. For this, just add a class called "dodisplay":
PLAIN TEXT HTML:<p><a href="ordered.html" class="codeexample dodisplay highlight[10,12,14-15]">ordered.html (click to show output)</a></p>
The script is creative commons, and hopefully you'll find some extras to add. Enjoy.
