Added on: Wednesday 24th August 2011
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!)
highlight.js is a javascript library releases by Software Maniacs and setting it up couldn't be easier because it automatically recognises the scripting language - well, as long as you use one of the 41 that it knows about.
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.
The javascript reference is:
<script src="http://yandex.st/highlightjs/6.0/highlight.min.js"></script>
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!)
$("p.code_block").each(function(){
var txt = $(this).html();
$(this).replaceWith('<pre><code>'+txt+'</code></pre>');
});
Except I've found a problem. As the code above contains < and > characters to show the html being output, it isn't formatted. If I take that line out it recognises it as javascript
Andrew Parrott runs Round Ash Associates, a web design and development company based in Chagford on Dartmoor, Devon.
If you prefer updates via email then please enter your email address below and click Submit.
If you haven't been to Chagford before then take a look a what you are missing.
Sitepoint is an indespensible resource for web designers.
Internet Explorer isn't the only web browser and from a development point of view Firefox is much better.
As many of the articles on this site are slightly techy I thought I ought to link to a glossary of Internet terms.
The layout for this site uses one of Matthew James Taylors 'liquid layouts'.
©Round Ash Associates 2009. Powered by form2list.