Adding code samples with SyntaxHighlighter 3.0

When you’re writing a technical post on coding, it’s important to be able to post code samples to show people exactly what you mean (and make it easier for them to cut and paste). But the standard behaviour for the <code> tag only forces the browser to render in a fixed-width font:

$(function() { $( "#button" ).click(function(){ $( ".classOld" ).switchClass( "classOld", "classNew", 1000 ); return false; }); });


Garbage, right? If you add the <pre> tag, you get your tabs and formatting back:

$(function() {
    $( "#button" ).click(function(){
        $( ".classOld" ).switchClass( "classOld", "classNew", 1000 );
        return false;
    });
});

That’s a bit better, but what we’re really missing is the pretty colors that help us parse the code semantics.

$(function() {
    $( "#button" ).click(function(){
        $( ".classOld" ).switchClass( "classOld", "classNew", 1000 );
        return false;
    });
});

That’s more like it! This code highlighting is the result of a fantastic open-source tool by Alex Gorbatchev called Syntax Highlighter, which you can find at http://alexgorbatchev.com/SyntaxHighlighter/.

Basic usage

1. Download the syntax highlighter package from the download page and install it somewhere where it is open to the web.
2. Insert the following code into the head of your html file, making sure to replace the paths with the correct paths for your installation (there is also a hosted version at http://alexgorbatchev.com/pub/sh/current/).

<script type="text/javascript" src="scripts/shCore.js"></script>
<script type="text/javascript" src="scripts/shBrushJScript.js"></script>
<script type="text/javascript" src="scripts/shBrushXml.js"></script>
<link href="styles/shCore.css" rel="stylesheet" type="text/css" />
<link href="styles/shThemeDefault.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
     SyntaxHighlighter.all()
</script>
3. Insert the following into your html body:
<pre class="brush: js">
$(function() {
    $( "#button" ).click(function(){
        $( ".classOld" ).switchClass( "classOld", "classNew", 1000 );
        return false;
    });
});
</pre>

And you have a basic code syntax highlighter running. Check out the configuration options if you want more control.

Notes:

Make sure to include the appropriate brushes for the syntax you want to show. This example includes the Javascript (“shBrushJScript”) brush and the HTML (“shBrushXml”) brush.
The vertical scroll bar shows up in Safari and Chrome because there is a 1 px offset introduced. This can be corrected by adding a pixel of padding to the .syntaxhighlighter class in the shCore.css file. Not the most elegant solution, but it works.

.syntaxHighlighter {
  padding: 0 1px !important;
...
}