Monday, January 28th, 2008p>One 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:
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:
You can highlight lines of code in the same manner, say you want like 18 to 20 in bold:
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":
The script is creative commons, and hopefully you'll find some extras to add. Enjoy.
Posted by Chris Heilmann at 11:18 am