Adding js and css syntax highlighting to page

Aug 25, 10:07 PM

I’d like to try to add a syntax highlighting feature to this site. I recall some js and css works that do just that. The feature’s purpose is to clarify the information on the site, making codes obvious and easy to digest, pretty to the eyes. Code is not always boring, it might as well be colourful!

As a result of digging around the web, I’ve found a couple of method to do this. I take the simplest and fastest to implement on this site, which is prettify by mikesamuel. This snippet is really simple and easy to use. Just needed some additional lines in the template code.

Download, upload, and link and looks more or less like this in your template HTML head section.

<script type="text/javascript" src="prettify/prettify.js"></script>
<link rel="stylesheet" type="text/css" href="prettify/prettify.css" />

That’s for the linking part. Now on to loading part. Modify your body opening tag so it look like this.

<body onload="prettyPrint()">

Done for the prettify section. On to the next problem.

I dont want to modify my published article just for the sake of adding prettyprint class to each of pre tags. To resolve this problem, I decided to use jQuery. Following the same process like prettify, download, upload, and link. In the head section:

<script type="text/javascript" src="jquery.js"></script>

and add new snippet of code somewhere in the head after the above link statement.

<script type="text/javascript">
    $(document).ready(function() {
        $("pre").addClass("prettyprint");
    });

What that snippet does is append prettyprint class to every pre tags in the current page, enabling prettify to capture and prettify them. All this without changing the source data.

Nice and easy, thanks prettify and jQuery developers!

Archayl Wizzpunk

Web design, Web development

Comment

Commenting is closed for this article.