CodeColorer Auto Expanding Code

Just quick post on a small feature I’ve just added to the site which I thought I’d share. It’s a slight addition to the CodeColourer plug-in for WordPress. CodeColourer formats and colourises code blocks in your blog posts for better readability. It comes with several different styles built in, or you can customise it using your own CSS file.

A feature that I saw on another site (although I can’t remember which) was when a user rolled over a code box it would expand to fit the code, allowing the user to see everything. Cool little addition, so I decided to create my own using jQuery. I’ve taken some of the code from the plug-in and pasted it below so you can see it in action:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
if($(".codecolorer-container").length){
    var $code = $(".codecolorer-container").each(function(){
        var $this = $(this);

        //Animation decision object
        var decisionObject = {
            w: false,
            h: false
        };

        //Original width / height of the displayed code
        var originalWidth = $this.width();
        var originalHeight = $this.height();

        //Width / height of hidden portion of code
        var mainWidth = $this.find(".codecolorer").width();
        var mainHeight = $this.find(".codecolorer").height();
        var lineWidth = $this.find(".line-numbers").width();

        //Only attach events if needed (ie has scroll bars)
        if((mainWidth + lineWidth) > originalWidth || mainHeight > originalHeight){
            /* and so on...... */
        }
    }
}

Since this action is fired on hover, I didn’t want the code boxes expanding immediately every time a user hovers over a box; as just scrolling down the page would expand the boxes which would become extremely annoying. The boxes should only expand when the cursor is left over the box; lucky there’s a plug-in for jQuery that already adds this functionality, it’s called $.event.special.hover.

Special hover simply replaces the standard hover event with one that monitors the speed of the cursor over a set period of time. If the cursor speed drops below the threshold the hover event fires. This is enough to stop random hover events firing when a user navigates over the page, simple!

I’d be interested to see if the code works for others using CodeColorer, there’s no reason why it shouldn’t.

Loading

Webmentions