HTML5 Pre/Code Syntax Highlighting with JavaScript

Performing a quick search in Google will yield a number of helpful JavaScript libraries for styling source code. Blogs and websites focused on frontend and backend development will frequently need to publish articles which use direct source code in the page. Basic monospaced fonts are not always enough, and with dynamic syntax highlighting it is much easier to implement this functionality than ever before.

In this tutorial I want to focus on using JavaScript to style your various code snippets. Syntax highlighting can be accomplished through a number of plugins, but in this example I will be using Rainbow syntax highlighter. It does not require any dependencies to run properly. And you may customize your own output file by editing the choices right from the Rainbow landing page. If you want to get a taste of how this all works, check out my sample demo below.

Live DemoDownload Source Code

Setting Up

First we need to download a copy of Rainbow from the main website, or download the full repository off Github. The latter is useful when you want to choose specific CSS themes for your syntax colors, and when you will be including separate language files inside your website HTML. If you want to choose a custom set of languages which are all compiled into one JS file select the Download button from the Rainbow homepage.

<script type="text/javascript" charset="utf-8" src="js/rainbow-custom.min.js"></script>
<!-- 
* we only need these libraries when not using a customized source *
* generate your own source from Rainbow's homepage: http://craig.is/making/rainbows *
<script type="text/javascript" charset="utf-8" src="js/rainbow.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/language/generic.js"></script>
<script type="text/javascript" charset="utf-8" src="js/language/html.js"></script>
<script type="text/javascript" charset="utf-8" src="js/language/css.js"></script>
-->

The above block of codes shows the differences between choosing separate files or building your own customized script. The resources which are commented using HTML will not be included in my demo, but you can see how they would be needed as separate files. It all depends on your use of Rainbow and how frequently you will be including source code samples. I find that a single file is easier on HTTP requests, so regardless of filesize it is a better solution for any typical webmaster.

I have also included three CSS resources which we need for displaying the layout properly. My sample header codes includes a Google Web Fonts resource, along with default CSS resets and page design. The 3rd CSS file is selecting a syntax highlight theme which will style the colors and background of each <code> or <pre> element.

<link rel="stylesheet" type="text/css" media="all" href="css/styles.css">
<link rel="stylesheet" type="text/css" media="all" href="css/themes/twilight.css">
<!-- Alternate themes: tomorrow-night.css, blackboard.css, all-hallows-eve.css -->
<link rel="stylesheet" type="text/css" media="all" href="http://fonts.googleapis.com/css?family=Bubblegum+Sans">

Notice that by default I am using the twilight.css theme, which works very nicely on darker websites. I did not include all of the various theme choices but there are some others you can play with. All of the alternate themes in my demo are designed specifically to blend into dark backgrounds, which is why I copied only these select choices. But all of the CSS themes are available in the Github repo if you want to give them a trial run.

Adding Sample Content

What makes Rainbow so attractive is that we do not need to run any special functions or methods. Other jQuery plugins will often require that you target a number of pre/code tags on the field. Or similarly you will need to include a small snippet of code at the footer area of your page to get the highlighted styles working.

But using Rainbow means that we just need to include the JS file and everything else will be handled by the script. The only variance to this rule is how you should structure each HTML element. There is a big list of languages you can see in the Github repo. For each pre/code block you will need to specify which syntax language is being used. Here is a sample of PHP code from my demo source:

<?php
$uploaddir = '/var/www/uploads/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);
echo '<p>';
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Upload failed";
}
echo '</p>';
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print '</pre>';
?>

The data attribute for data-language=”php” is created strictly for this JS library. HTML5-compliant browsers should recognize this as acceptable syntax, but even older legacy systems will still render the elements properly. And it is also possible to include this data-language attribute onto the <pre> tag if you are having trouble using the <code> element.

It is surprisingly easy to get all of this working properly. A bit of practice will be necessary if you want to use this script repeatedly in your website projects. The long list of syntaxes and CSS themes can become convoluted when trying to include everything into a CMS like WordPress or Drupal. But even with just a couple hours of practice you should be able to familiarize yourself with the concepts quickly and effortlessly.

Live DemoDownload Source Code

Final Thoughts

What I like most about Rainbow is the ability to customize your own JS file for deployment. This means you have the ability to select a set number of languages and styles for your code blocks, pre-determined for each website’s specific needs. Syntax highlighting is fairly easy when you know which languages will be used. And following this method will produce a much smaller, compressed file resource to include within your webpage.

I do hope this tutorial can help some developers who are in need of a solid JavaScript library for syntax highlighting. The Rainbow JS script is super easy to learn, and it is even possible to extend Craig’s original library with your own custom syntaxes. If you have any questions or additional comments on the tutorial feel free to share with us in the post discussion area below.

DesignWoop Newsletter

Sign up to the DW newsletter, occasionally we send design & development related freebies, offers and exclusive deals.

Comments are now closed.