Blog

Where we discuss our work, thoughts, and process

jQuery Content Expansion: Give your code more breathing room

We often write about code on our site, so it makes sense to show the code. While the <pre> tag is simple, the code never looks as good as it does in your editor. Fortunately there is a great javascript package called SyntaxHighlighter by Alex Gorbatchev that makes adding syntax highlighting to your site easy. Simply include the script and css and add classes to your pre tags that let it know what language you are using. On our site we use the following classes:

  • brush:html
  • brush:php
  • brush:js
  • brush:css

Here is an example on how include some html code on your site that is syntax highlighted:

<pre class="brush:html">
	<h1>Hello World</h1>
</pre>

This is super-simple, but we quickly noticed one issue: the code we wanted to post required way too much wrapping. I had seen Viget, a fellow NC web agency handle this problem with elegance, but as you can see in their example, they don't use their expanding solution on SyntaxHighlighted blocks.

Their approach was solid and easy to extend once I understood what happened to my markup once SyntaxHighlighter ran. All I needed to do was wrap the <pre> tags twice, once to make a wide space and once to make a "window" that was the width of the content. You can see roughly what I mean below:

The jquery to do this wrapping looks like this:

$('pre, .syntaxhighlighter').wrap('<div class="brushwindow"></div>').wrap('<div class="brushwrap"></div>');

After this runs, the markup is as follows:

<div class="brushwindow">
	<div class="brushwrap">
		<div class="syntaxhighlighter">
			[code]
		</div>
	</div>
</div>

To get the styling right we need to add a little css. Note the "overflow: hidden;" on the window. That is what cuts off the code we don't want to see.

.brushwindow { z-index: 99; width: 560px; overflow: hidden;  }
.brushwrap { width: 848px; }

Finally we need to add the javascript that grows the size of the window div when we hover over it.

$('.brushwindow').hover(function(){
	$(this).animate({width: '850px'});
}, function() {
	$(this).animate({width: '560px'});
});

While not particularly difficult to implement, it makes code blocks much more usable. You can see it in action on this post, but the effect is muct more dramatic on a post that Josh recently wrote about a jQuery Calendar we did.

Leave the first comment