Code snippets with SyntaxHighlighter and jQuery

This post shows how to display code snippets (small sections of source code) in a WordPress site using SyntaxHighlighter and jQuery.  The result is jpmec.snippet, a simple, free code JavaScript snippet tool for blog posts.

Show me

Below is an example of the jpmec.snippet tool. (Note, it works best with recommended browsers.)

function foo () {
	var bar = "tar tar";

You can also look the source code.

Yet another syntax highlighter?

No, not exactly.  Instead, it uses SyntaxHighlighter along with jQuery to make stylish, collapsible code snippet sections in a WordPress blog post.

Is it easy to use?

I hope so 🙂  The story behind jpmec.snippet is,

“As a blog author, I want to be able to add collapsible code snippets easily to my WordPress blog posts.”

After searching the Internet, I found SyntaxHighlighter, a syntax highlighting tool written in JavaScript.  This tool formats source code nicely, however it isn’t collapsible by default.  The jQuery library, which is included with WordPress, can be used to easily show and hide elements in a web page.

To use jpmec.snippet, you will need to install jpmec.snippet.js and jpmec.snippet.css on your site.

First, define your code snippet with a <pre id='your_id' class='snippet'></pre> element.  (Note, the <pre> element is useful because if the client browser doesn’t support JavaScript, or there is an error, then the snippet is rendered in a monospace font.)

Last, call Snippet.all() after your page has loaded.  The easiest way to do this, is add the following script to the end of your blog post.

<script type="text/javascript">
	function() { Snippet.all(); }

That’s all folks! Now you should be able to use collapsible code snippets in a blog post.