Syntax highlighting on web pages
Added on: Wednesday 24th August 2011
I've recently been looking at various solutions for highlighting code snippets as I wanted something to make it easier to publish on this blog. I've settled on highlight.js as it is so simple.
Part of the reason I haven't published an article for a while is that I wanted a better way of displaying the code than I had before. (The other reason is lack of time!)
To add the feature to a web site you just have to reference a script file and a stylesheet. These are both hosted on external servers so you don't even need to download them.
and the stylesheet reference is:
<link rel="stylesheet" href="http://yandex.st/highlightjs/6.0/styles/default.min.css">
If you want a style other than the default just replace default in the url above with the name of the style. (see the site for available styles).
Thats about it, except that you have to initialise the script when the page loads - after that it will format any code within <pre><code> tags.
I had a slight problem here in that I use WymEditor for my blog which doesn't easily allow me to wrap text within these two elements.
However, a bit of jquery soon sorted this. Within the editor, I give any code a class of code_block. The jquery then goes to work on each element with this class and wraps the contents in <pre><code> tags.
I've included the script below (because I can highlight it now!)
var txt = $(this).html();