Beautify Your jQuery Code Using beautify.js

Sam Deering

It can be very time consuming to make your jQuery code neat and tidy. Fortunately, there are online tools and heaps of plugins that can automate this task for us. I recently had the need to generate JavaScript/jQuery code dynamically and thus it comes through messy and unreadable. So I decided to use beautify.js to neaten jQuery code so it is uniform, tidy and people can read it. I have extensively used this to neaten the jQuery code in the function demos section of the blog. Just click on “View Code” to see it in action on any of the function example pages.

beautifier-demo

With syntax highlighter applied.
finished
Live Demo
Download Demo Package

Instructions

  1. Download beautify package from GitHub.
  2. Modify the code to suit your setup (ie – I didn’t need the obfuscation unpackers so I removed them to reduce unused code and I then added in a parameter to the beautify function so that it can apply the beautifier to a specific element then looped the elements of class=”raw” which contain the jQuery code).
  3. Include the beautifier call in a DOM ready and then after you could apply a syntax highlighter if you wish. You can use one of these 10 syntax highlighters.

The Code

Include the scripts.

<script src="js/beautify.js"></script>
<script src="js/beautify-html.js"></script>
<script src="js/mybeautifier.js"></script>
/* beutify all code with class="raw" */
$(document).ready(function() {
    $('.raw').each(function()
    {
        beautify(this);
    });
});

[/js]

Specify your code elements inside a pre tag with class="raw".

1
<pre class="raw"><!-- your code here --></pre>

I have modified version of beautify() function and removed the code unpacker functions and put them into a new file called “mybeautifier.js”. The contents of this file:

var the = {
    beautify_in_progress: false
};

// this dummy function alleviates Chrome large string corruption by probably shoveling the corruption bug to some other area
if (/chrome/.test(navigator.userAgent.toLowerCase())) {
    String.prototype.old_charAt = String.prototype.charAt;
    String.prototype.charAt = function (n) { return this.old_charAt(n); }
}

function unpacker_filter(source) {
    var trailing_comments = '';
    var comment = '';
    var found = false;

    do {
        found = false;
        if (/^s*/*/.test(source)) {
            found = true;
            comment = source.substr(0, source.indexOf('*/') + 2);
            source = source.substr(comment.length).replace(/^s+/, '');
            trailing_comments += comment + "n";
        } else if (/^s*///.test(source)) {
            found = true;
            comment = source.match(/^s*//.*/)[0];
            source = source.substr(comment.length).replace(/^s+/, '');
            trailing_comments += comment + "n";
        }
    } while (found);

    return trailing_comments + source;
}


function beautify(elem) {
    if (the.beautify_in_progress) return;

    the.beautify_in_progress = true;
    var source = $(elem).html();

    var indent_size = $('#tabsize').val();
    var indent_char = indent_size == 1 ? 't' : ' ';
    var preserve_newlines = $('#preserve-newlines').attr('checked');
    var keep_array_indentation = $('#keep-array-indentation').attr('checked');
    var brace_style = $('#brace-style').val();

    if ($('#detect-packers').attr('checked')) {
        source = unpacker_filter(source);
    }

    var comment_mark = '<-' + '-';
    var opts = {
                indent_size: indent_size,
                indent_char: indent_char,
                preserve_newlines:preserve_newlines,
                brace_style: brace_style,
                keep_array_indentation:keep_array_indentation,
                space_after_anon_function:true};

    if (source &amp;&amp; source[0] === '<' &amp;&amp; source.substring(0, 4) !== comment_mark) {
        $(elem).html(
            style_html(source, opts)
        );
    } else {
        var v = js_beautify(unpacker_filter(source), opts);
        $(elem).html(v);
    }

    the.beautify_in_progress = false;
}

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.gbin1.com terry

    it does NOT work in IE

    • jquery4u

      Unfortunately, I’ve only tested in FF5, Chrome 12 and IE9.

      Which version of IE was being IE?

  • http://www.pure-tentation.fr syndrael

    Live demo button doesn’t target to the wanted page.. i think so.

    • jquery4u

      @syndrael, It goes to the function demo pages, which are running the code, just click “View Code” to see it in action.