Hostinicon
GET HOSTING FROM $3.95/MO PLUS A FREE YEAR ON TUTS+ (RRP $180). HURRY OFFER LIMITED. Check it out
Advertisement

Quick Tip: How to Add Syntax Highlighting to Any Project

by
Gift

Get a free year on Tuts+ this month when you purchase a Siteground hosting plan from $3.95/mo

In this lesson, we'll use a JavaScript based syntax highlighter to quickly add a syntax highlighting functionality to any web project — even on a simple HTML page!


Step 1 — Download the Source Code

You can download the syntax highlighter source files here.


Step 2 — Drag the src Directory into your Project

I generally rename this folder to highlighter. Don't delete anything within here, unless you don't anticipate using some of the language specific JavaScript files.


Step 3 — Import the Necessary Files

Within your HTML file (or whichever page is responsible for displaying your view), import both the prettify.css and prettify.js files.

Notice how we've placed our script at the bottom of the page, just before the closing body tag. This is always a smart move, as it improves performance.

Next, we need something to work with! The syntax highlighter will search for either a pre or code element that has a class of prettyprint. Let's add that now.


Step 4 — Calling the prettyPrint() Function

The last step is to execute the prettyPrint() function. We can place this bit of code at the bottom of the page as well.

If we now view the page in the browser...

final product

Well that was easy! But, as a final bonus step, what if we want to change the highlighter theme? In that case, it all comes down to editing the stylesheet how you see fit. Even better, there are a handful of stylesheets in the theme gallery that you're free to use. I personally like the Desert theme. To apply it, copy the CSS from the link above, create a new stylesheet in your project, and paste the CSS into it. Next, update the stylesheet include from within the head section of your document.

Desert Theme Applied

Seriously — can it get any simpler than that?

Advertisement