Tumblr Blog Theme Javascript

I didn’t expect that I’d need to write custom javascript for this blog’s theme, but it turns out I wanted three things that are kinda weird.

First, I wanted automatic syntax coloring. prettify.js rocks but like Ryan I use Markdown and don’t want to break out of its one-tab-to-insert-code feature just to add a prettyprint class. Solution:

    $("pre code").each(function(){

Note 1: Ryan’s code seems broken on the current (21-May-2009) version of prettify.js — I had to modify it to apply the class to the block’s code element, not the pre element.

Note 2: you need to put your call to prettyPrint() here. Previously I had it at the end of my HTML inside a <script type="text/javascript">prettyPrint();</script> tag. That doesn’t work because prettyPrint() fires before the class-annotator.

Second, I wanted a shortish line width, but my lines of code can get long. So I decided to just hide the overflow, but when you hover the overflow is made visible.

I coded that up in pure CSS, but then remembered there is no hover on the iPhone. So I added the ability to “click open” a code block and have it stick:

// Toggle overflow on code blocks.
$('head').append($("<style type='text/css'>pre{overflow:hidden}<\/style>"));
}, function(){

That little call to $('head').append() is so I only hide the overflow when Javascript is loaded. If you’re running with it off, I decided I’d rather have everything visible (but ugly) than go off hiding things on you and giving you no way to make it visible.

Finally, I wanted to easily insert Flickr images, but didn’t want to hard-code their size to my current layout. A little-known fact about HTML is that browsers are willing to Do The Math for you if you specify a <img>'s width but not its height. Sadly, this feature doesn’t extend to CSS’s max-width, so it’s back to the Javascript mines:

var maxWidth = $('.post_body').width();
    var scaledHeight;
    if (this.width > maxWidth) {
        scaledHeight = (this.height * maxWidth) / this.width;
        this.width = maxWidth;
        this.height = scaledHeight;

js javascript tumblr theme jquery Nov 2 2009