Justin Paul Silva

Syntax Highlighting for Your Blog

Posted on

One of the greatest things about code editors is syntax highlighting. It makes any kind of code or markup language easier to read and understand. So why not use the same highlighting in your <code> blocks on your blog or website? When I created this site (just this week), syntax highlighting was one thing I knew I needed to have. So I did some searching, and it turns out to be incredibly easy to set up.

I decided on JavaScript Syntax Highlighter (or JUSH). It’s available as a stand-along script, a jQuery plugin, and a WordPress plugin. I’ll explain how to use it with jQuery, since that’s how I’m using it and they don’t cover it on their website.

First, download the Javascript and CSS files from the JUSH homepage. Then, include the files in your webpage:

<link rel="stylesheet" type="text/css" href="jush.css" /> <script type="text/javascript" src="jush.js"></script>

I differentiate between different coding languages by using the class attribute of the <code> element:

<code class="html"> <div id="content">Some HTML content</div> </code> <code class="html"> <div id="more_content">Some more HTML content</div> </code> <code class="css"> #content { color:#cc0000; } </code> <code class="js"> $('#content').html('Some Javascript content'); </code>

Then, I style it with:

// Syntax Highlighting $("code.html").each(function(){ $(this).jush('htm'); }); $("code.js").each(function(){ $(this).jush('js'); }); $("code.css").each(function(){ $(this).jush('css'); });

It seems you should be able to do…

$("code.html").jush('htm'); $("code.js").jush('js'); $("code.css").jush('css');

… but for some reason, it will take the content from all “html” code blocks on the page and combine them, so that both in the above code would output…

<div id="content">Some HTML content</div><div id="more_content">Some more HTML content</div>

… which clearly is not what we want.

So that’s it. Easy, wasn’t it? The only styling left for your <code> blocks is to use proper white space, either by wrapping your code blocks with <pre> tags, or using white-space:pre; in your stylesheet.