Home arrow JavaScript arrow JavaScript Syntax Highlighter: beautyOfCode
JAVASCRIPT

JavaScript Syntax Highlighter: beautyOfCode


In this JavaScript article, we review - and show you how to implement - the JavaScript syntax highlighter, beautyOfCode.

Author Info:
By: Alejandro Gervasio
Rating: 5 stars5 stars5 stars5 stars5 stars / 2
August 08, 2011

print this article
SEARCH DEVARTICLES

In this JavaScript article, we review - and show you how to implement - the JavaScript syntax highlighter, beautyOfCode.

If you’re planning to use a JavaScript syntax highlighter to give your online code samples a more readable and refreshing touch, and are still uncertain which code highlighter you should use, this tutorial (and its previous parts) should help make your decision a whole lot easier.

If you’ve been a loyal reader and went through the two installments that precede this one, at this stage you’re familiar with the features offered by some of the aforementioned libraries, as in the course of those articles I took an in-depth look at four powerful contenders in the field, including Alex Gorbatchev’s SyntaxHighlighter, SHJS (Syntax Highlighting in JavaScript), Highlight.js  and Google Code Prettify.

If you missed those articles (or would like a refresher) you can find them here:

http://www.devarticles.com/c/a/JavaScript/Popular-JavaScript-Syntax-Highlighters/
http://www.devarticles.com/c/a/JavaScript/More-of-the-Best-Javascript-Syntax-Highlighters/

While it’s fair to admit that these packages yield remarkable results when it comes to improving the look and readability of code fragments in (X)HTML pages, there’s still one final library that deserves a close analysis, due to its current popularity and the plethora of facilities that it brings to the table. Yes, as you may have guessed from the article’s title, in this case I’m making reference to beautyOfCode (http://startbigthinksmall.wordpress.com/2008/10/30/beautyofcode-jquery-plugin-for-syntax-highlighting/), a jQuery plug-in which acts like a solid wrapper for SyntaxHighlighter, and that adds some extra features to the core package, boosting its existing functionality.  

With that being said, in this last post I’ll be demonstrating the goodies provided by this jQuery plug-in, and how to put it into action. 

Summary Time: A Quick Look at Some Previous Syntax Highlighters

Before I start showing you how to work with the beautyOfCode jQuery plug-in, I’d like to spend a few moments recapping the syntax highlighters that were discussed in the previous installment of this tutorial.

The first of these libraries is a lightweight one called Highlight.js. Below is a basic example that demonstrates how to use it with a small PHP fragment. Have a look:

<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Using highlight.js Syntax highlighter (default theme)</title>
<!-- Include the JavaScript dependencies -->
<script src="highlight/highlight.pack.js"></script>
<!-- Include the default styles -->
<link rel="stylesheet" href="highlight/styles/default.css">
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: 1em Arial, Helvetica, sans-serif;
    color: #000;
}
#wrapper {
    width: 800px;
    margin: 0 auto;
}
</style>
</head>
<body>
    <div id="wrapper">
        <header>
            <h1>Using highlight.js Syntax highlighter (default theme)</h1>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>
        </header>
        <section id="code-section">
            <header>
                <h2>Sample code section</h2>
            </header>
            <pre>
                <code>
    &lt;?php
   
    namespace SampleApp\Common;

    class ServiceLocator implements RegistrableInterface
    {
        protected $_resources = array();

        /**
         * Set the specified resource
         */
        public function set($key, AbstractResource $resource)
        {
            if (!isset($this-&gt;_resources[$key])) {
                $this-&gt;_resources[$key] = $resource;
            }
            return $this;          
        }

        /**
         * Get the specified resource
         */
        public function get($key)
        {
            if (isset($this-&gt;_resources[$key])) {
                return $this-&gt;_resources[$key];
            }
            throw new \InvalidArgumentException('The requested resource does not exist.');
        }

        /**
         * Remove the specified resource
         */
        public function remove($key)
        {
            if (isset($this-&gt;_resources[$key])) {
                unset($this-&gt;_resources[$key]);
                return $this;
            }
            throw new \InvalidArgumentException('The resource to be removed does not exist.');
        }
         
        /**
         * Check if the specified resource exists
         */
        public function exists($key)
        {
            return isset($this-&gt;_resources[$key]);
        }     
    }
                </code>
            </pre>
        </section>
        <footer>
            <header>
                <h2>Footer section</h2>
            </header>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>
        </footer>
    </div>
    <script>
    // highlight the code section
    hljs.initHighlightingOnLoad();
    </script>   
</body>
</html>

Getting Highlight.js up and running is a straightforward process reduced to including a pair of dependencies (namely its main JavaScript file and the corresponding CSS theme) and lastly calling its “initHighlightingOnLoad()” method, once the web page has finished loading.

The above example looks like this in the browser:

Even though Highlight.js doesn’t come packaged with some of the additional features provided by other highlighters, such as lnumbering and toolbars, it does a more than decent job when it comes to improving the visual presentation of online code fragments. Certainly, an option worth taking into account. 

And now that you grasped how Highlight.js does its thing, it’s time to move on and pay attention to the next player of this overview - Google Code Prettify, the handy code beautifier created by the giant search company.

Along the lines of other applications released in the last few years, Google Code Prettify is a snap to setup and use. Of course, the best way to demonstrate this is with a concrete example. So below I created a new one, which uses the library for highlighting the same PHP portion that you saw before. Here it is: 

<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Using Google Code Prettify Syntax highlighter</title>
<!-- Include the JavaScript dependencies -->
<script src="google-code-prettify/prettify.js"></script>
<!-- Include the default styles -->
<link href="google-code-prettify/prettify.css" type="text/css" rel="stylesheet" />
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: 1em Arial, Helvetica, sans-serif;
    color: #000;
}
#wrapper {
    width: 800px;
    margin: 0 auto;
}
</style>
</head>
<body>
    <div id="wrapper">
        <header>
            <h1>Using Google Code Prettify Syntax highlighter</h1>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>
        </header>
        <section id="code-section">
            <header>
                <h2>Sample code section</h2>
            </header>
            <pre class="prettyprint">
                <code>
    &lt;?php
   
    namespace SampleApp\Common;

    class ServiceLocator implements RegistrableInterface
    {
        protected $_resources = array();

        /**
         * Set the specified resource
         */
        public function set($key, AbstractResource $resource)
        {
            if (!isset($this-&gt;_resources[$key])) {
                $this-&gt;_resources[$key] = $resource;
            }
            return $this;          
        }

        /**
         * Get the specified resource
         */
        public function get($key)
        {
            if (isset($this-&gt;_resources[$key])) {
                return $this-&gt;_resources[$key];
            }
            throw new \InvalidArgumentException('The requested resource does not exist.');
        }

        /**
         * Remove the specified resource
         */
        public function remove($key)
        {
            if (isset($this-&gt;_resources[$key])) {
                unset($this-&gt;_resources[$key]);
                return $this;
            }
            throw new \InvalidArgumentException('The resource to be removed does not exist.');
        }
         
        /**
         * Check if the specified resource exists
         */
        public function exists($key)
        {
            return isset($this-&gt;_resources[$key]);
        }     
    }
                </code>
            </pre>
        </section>
        <footer>
            <header>
                <h2>Footer section</h2>
            </header>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>
        </footer>
    </div>
    <script>
    // highlight the code section
    prettyPrint();
    </script>   
</body>
</html>

As you can see, Google Code Prettify functions quite similar to its competitor Highlight.js, as it also needs only a couple of dependencies to work as intended. The utility requires you to add a class called “prettyprint” to the <pre> element that wraps the sample code, a process that in this particular case generates the following result:

Google Code Prettify does a great job of enhancing the appearance of code snippets included in (X)HTML pages, not to mention the fact that it offers a few others facilities for free, such as custom line numbering and a decent variety of CSS themes (http://google-code-prettify.googlecode.com/svn/trunk/styles/index.html). In summary, it is a rich featured package that’s both easy to configure and use.

So far, so good. Having demonstrated how to get started using Google’s handy highlighter, it’s time to leap forward and take a close look at the final contender of this review. In consonance with the concepts deployed in the introduction, this one is a jQuery plug-in called beautyOfCode, which surely you’ll be familiar with, as it’s used widely around the web.

Reviewing a Final Contender: Working with beautyOfCode’s jQuery Plug-in  

If you still haven’t given a try to beautyOfCode (http://startbigthinksmall.wordpress.com/2008/10/30/beautyofcode-jquery-plugin-for-syntax-highlighting/) you should, because it’ll put a big smile on your face as soon as you start using it. Created by Lars Corneliussen, the library is a jQuery plug-in which behaves like a clean wrapper for Alex Gorbatchev’ SyntaxHighlighter.

Preserving the handy facilities included in the original package, beautyOfCode incorporates a few more, something that has turned it into one of the most popular full-featured JavaScript highlighters available today. Add to this the fact that the library is very easy to setup and use, and you’ll realize why it’s a hard-to-beat contender in the field.   

Of course, if you’re anything like me, you want to see the actual functionality of beautyOfCode in a concrete use case. Below I created another basic example, which shows you how to utilize the package to beautify the same PHP snippet that you saw in the previous segment. Take a look at it:

<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Using beautyOfCode Syntax highlighter</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="jQuery.beautyOfCode/jquery.beautyOfCode-min.js"></script>
<script>
    $.beautyOfCode.init({
      brushes: ['Php']
    });
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
#wrapper {
    width: 800px;
    margin: 0 auto;
}
</style>
</head>
<body>
    <div id="wrapper">
        <header>
            <h1>Using beautyOfCode Syntax highlighter</h1>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>
        </header>
        <section id="code-section">
            <header>
                <h2>Sample code section</h2>
            </header>
            <pre class="code">
                <code class="php">
                &lt;?php
               
                namespace SampleApp\Common;

                class ServiceLocator implements RegistrableInterface
                {
                    protected $_resources = array();

                    /**
                     * Set the specified resource
                     */
                    public function set($key, AbstractResource $resource)
                    {
                        if (!isset($this-&gt;_resources[$key])) {
                            $this-&gt;_resources[$key] = $resource;
                        }
                        return $this;          
                    }

                    /**
                     * Get the specified resource
                     */
                    public function get($key)
                    {
                        if (isset($this-&gt;_resources[$key])) {
                            return $this-&gt;_resources[$key];
                        }
                        throw new \InvalidArgumentException('The requested resource does not exist.');
                    }

                    /**
                     * Remove the specified resource
                     */
                    public function remove($key)
                    {
                        if (isset($this-&gt;_resources[$key])) {
                            unset($this-&gt;_resources[$key]);
                            return $this;
                        }
                        throw new \InvalidArgumentException('The resource to be removed does not exist.');
                    }
                     
                    /**
                     * Check if the specified resource exists
                     */
                    public function exists($key)
                    {
                        return isset($this-&gt;_resources[$key]);
                    }     
                }
                </code>
            </pre>
        </section>
        <footer>
            <header>
                <h2>Footer section</h2>
            </header>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>
        </footer>
        <script>
        // highlight the code section
        SyntaxHighlighter.all();
        </script>
    </div>   
</body>
</html>

From the above example, it is evident that working with beautyOfCode is a breeze. In this case, I specified a “Php” brush within its “init()” method, since the code being highlighted is effectively PHP. It’s possible, however, to work with multiple brushes at the same time, which obviously comes in handy when it’s necessary to display code samples that span several languages.

But before I proceed to demonstrate how to achieve this, first off have a look at the following screen capture, which depicts the output generated by the earlier example:

If you’re a savvy user who stops by technical blogs and ezines on a frequent basis, the above image should be pretty familiar to you, as beautyOfCode is used all over the place. But, as I just said a moment ago, the library allows you to beautify many other languages other than PHP as well.    

If you’re wondering how to do this, be sure to check the below example, which this time uses the package’s functionality for highlighting the previous PHP snippet along with a short JavaScript function:

<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Using beautyOfCode Syntax highlighter (with multiple brushes)</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="jQuery.beautyOfCode/jquery.beautyOfCode-min.js"></script>
<script>
    $.beautyOfCode.init({
      brushes: ['JScript', 'Php']
    });
</script>
<style type="text/css">
body {
    padding: 0;
    margin: 0;
    background: #fff;
    font: 0.8em Arial, Helvetica, sans-serif;
    color: #000;
}
#wrapper {
    width: 800px;
    margin: 0 auto;
}
</style>
</head>
<body>
    <div id="wrapper">
        <header>
            <h1>Using beautyOfCode Syntax highlighter</h1>
                <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>
        </header>
        <section id="code-section">
            <h2>PHP snippet</h2>
            <!-- PHP snippet -->
            <pre class="code">
                <code class="php">
                &lt;?php
               
                namespace SampleApp\Common;

                class ServiceLocator implements RegistrableInterface
                {
                    protected $_resources = array();

                    /**
                     * Set the specified resource
                     */
                    public function set($key, AbstractResource $resource)
                    {
                        if (!isset($this-&gt;_resources[$key])) {
                            $this-&gt;_resources[$key] = $resource;
                        }
                        return $this;          
                    }

                    /**
                     * Get the specified resource
                     */
                    public function get($key)
                    {
                        if (isset($this-&gt;_resources[$key])) {
                            return $this-&gt;_resources[$key];
                        }
                        throw new \InvalidArgumentException('The requested resource does not exist.');
                    }

                    /**
                     * Remove the specified resource
                     */
                    public function remove($key)
                    {
                        if (isset($this-&gt;_resources[$key])) {
                            unset($this-&gt;_resources[$key]);
                            return $this;
                        }
                        throw new \InvalidArgumentException('The resource to be removed does not exist.');
                    }
                     
                    /**
                     * Check if the specified resource exists
                     */
                    public function exists($key)
                    {
                        return isset($this-&gt;_resources[$key]);
                    }     
                }
                </code>
            </pre>
            <h2>JavaScript snippet</h2>
            <!-- JavaScript snippet -->
            <pre class="code">
                <code class="javascript">
                    // get the state of the form
                    function getFormState() {
                        var fields = document.getElementsByTagName('form')[0].elements;
                        if (fields.length == 0){return};
                        for (var i = 1; i &lt;= fields.length-1; i++) {
                            var name = fields[i].getAttribute('name');
                            if (name in localStorage &amp;&amp; localStorage[name] !== null) {
                                fields[i].value = localStorage[name];
                            }
                        }
                    }
                </code>
            </pre>
        </section>
        <footer>
            <header>
                <h2>Footer section</h2>
            </header>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse auctor commodo risus, et ultrices sapien vestibulum non. Maecenas scelerisque quam a nulla mattis tincidunt. Etiam massa libero, pharetra vel laoreet et, ultrices non leo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere ullamcorper lacus et sollicitudin. Morbi ultrices condimentum lacus, sit amet venenatis purus bibendum sit amet. Quisque rhoncus sodales sapien ac blandit. Nam lacus urna, commodo eget tincidunt vitae, ullamcorper at nulla. Vivamus ac iaculis justo.</p>
        </footer>
        <script>
        // highlight the code section
        SyntaxHighlighter.all();
        </script>
    </div>   
</body>
</html>

While this brand new example looks quite similar to the first one, it has some subtle differences worth noting: first off, the “init()” method now includes two brushes called “JScript” and “Php”, as there’re needed to highlight the corresponding code fragments. And last but not least, the <code> tags that wrap the fragments in question have been assigned in turn a “php” and “javascript” CSS class, something that lets the library deal with multiple languages simultaneously.

Finally, here’s how the prior JavaScript fragment looks after being parsed by beautyOfCode (its PHP-based counterpart has been omitted for the sake of brevity):

That worked like a charm. This shows in a nutshell that the library is not only capable of massaging several languages at the same time, but the whole cosmetic process that it performs behind the scenes is clean, simple, and unobtrusive.

To sum up: beautyOfCode is a top-notch player in the terrain of JavaScript highlighters that wraps and boosts the core functionality of SyntaxHighlighter. So, if you don’t mind including jQuery to make your online code samples look nice, beautyOfCode can be the option that you’re looking for. 

Final Thoughts

Sad but true, we’ve come to the end of this humble roundtrip on the five most popular JavaScript syntax highlighters. But at this moment you should have a clearer idea about how the reviewed packages do their business, and what they offer to the average web designer.

Maybe the concept is somewhat obvious, but even when the libraries that were put under analysis provide a bunch of appealing features right out the box, you don’t have to use them in every possible situation. In many cases, a slight dose of CSS can be good enough to convert arid and boring online code snippets into eye-catching and readable web page blocks.

Even so, if you’re planning to setup a new blog, or already drive the horses of a technical website that attracts a lot of traffic, picking up a syntax highlighter can be a good choice, specially if you’re delivering content that scopes a broad range of languages and technologies.

See you in the next web design tutorial!


DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

All JavaScript Tutorials
More By Alejandro Gervasio


blog comments powered by Disqus
JAVASCRIPT ARTICLES

- Project Nashorn to Make Java, JavaScript Wor...
- JavaScript Virus Attacks Tumblr Blogs
- Google Releases Stable Dart Version, JavaScr...
- Khan Academy Unveils New JavaScript Learning...
- Accessing Nitro? There`s an App for That
- JQuery 2.0 Leaving Older IE Versions Behind
- Fastest JavaScript Engine Might Surprise You
- Microsoft Adjusting Chakra for IE 10
- Brendan Eich: We Don`t Need Google Native Cl...
- An Overview of JavaScript Statements
- An Overview of JavaScript Operators
- Overview of JavaScript Variables
- More of the Top jQuery Social Plugins
- The Top jQuery Social Plugins
- More of the Top jQuery Slider Plugins

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials