Beautify Your jQuery Code Using beautify.js

Share this article

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);
    });
});
Specify your code elements inside a pre tag with class=”raw”.
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 && source[0] === '<' && 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;
}

Frequently Asked Questions about Beautifying jQuery Code with JS Beautify

What is JS Beautify and why is it important in jQuery coding?

JS Beautify is a tool used to format and beautify JavaScript code, making it easier to read and understand. It’s especially important in jQuery coding because it helps developers to quickly understand the structure and flow of the code, which can be complex and difficult to follow without proper formatting. JS Beautify also helps in identifying errors and debugging, as well-structured code is easier to troubleshoot.

How does JS Beautify work?

JS Beautify works by taking your raw, minified, or obfuscated JavaScript code and reformats it into a more readable and understandable format. It does this by adding appropriate indentation, line breaks, and spaces, making the code structure clear. It also helps in aligning assignment operators and ternary operators for better readability.

Can I use JS Beautify for languages other than JavaScript?

Yes, JS Beautify is not limited to JavaScript alone. It can also be used to beautify other languages like CSS and HTML. This makes it a versatile tool for web developers who work with multiple languages.

How can I use JS Beautify in my development environment?

JS Beautify can be integrated into various development environments. It’s available as a command-line tool, a web-based tool, and as a plugin for text editors and IDEs like Sublime Text, Visual Studio Code, and Atom. This makes it easy to use as part of your regular coding workflow.

Is JS Beautify compatible with ES6 and later versions of JavaScript?

Yes, JS Beautify is compatible with ES6 and later versions of JavaScript. It can handle new syntax and features introduced in these versions, ensuring your modern JavaScript code is formatted correctly.

Can JS Beautify handle minified code?

Yes, JS Beautify can handle minified code. It can take a single line of minified JavaScript code and reformat it into a multi-line, indented, and readable format. This is particularly useful when you need to understand or modify minified code.

Does JS Beautify preserve comments in the code?

Yes, JS Beautify preserves comments in the code. This is important because comments often contain important information about the code, and losing them during the beautification process would be undesirable.

Can I customize the formatting options in JS Beautify?

Yes, JS Beautify allows you to customize various formatting options, such as indentation size, maximum line length, and whether to use spaces or tabs for indentation. This allows you to format the code according to your personal preferences or your team’s coding standards.

Is JS Beautify free to use?

Yes, JS Beautify is a free and open-source tool. You can use it without any cost, and if you’re a developer, you can even contribute to its development on GitHub.

Can JS Beautify handle large files?

Yes, JS Beautify can handle large files. However, the processing time may increase with the size of the file. For very large files, it’s recommended to use a powerful text editor or IDE that can handle large amounts of data efficiently.

Sam DeeringSam Deering
View Author

Sam Deering has 15+ years of programming and website development experience. He was a website consultant at Console, ABC News, Flight Centre, Sapient Nitro, and the QLD Government and runs a tech blog with over 1 million views per month. Currently, Sam is the Founder of Crypto News, Australia.

jQuery
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week