Skip to content

June 18, 2009


How to use CSS SyntaxHighlighter 2.0 with Ajax/Prototype

by Joe Kuan

CSS SyntaxHighlighterThe default method to use SyntaxHighlighter 2.0 is via SyntaxHighlighter.all() declared in the Javascript section of the main page. What this method does is to register the SyntaxHighlighter.highlight() to call when the main page is loaded. The highlight method then searches for all the <PRE> tags (default configured tag name) and checks any class names containing the ‘brush:’ keyword. If so, then proceeds with syntax highlighting.

In Ajax environment, the content is not always available when the main page is loaded, an alternative way to call the highlight method is necessary. Suppose you have a <DIV> box and it’s content is updated dynamically through the innerHTML field. In Prototype, a typical example would be:

Ajax.Updater('div_box', 'display_file.php');

Inside the display_file.php, you probably have something like that:

<Textarea class='brush: bash'>
<?php echo file_get_contents($filepath); ?>

In order to call syntax highlight function, all you have to do is to simply change the Updater call to:

Ajax.Updater('div_box', 'display_file.php', {
              onComplete : function(t) {

Make sure you have configured SyntaxHighlighter.config.tagName to TextArea prior calling the Ajax.Updater.

Here are my other SyntaxHighlighter blogs
CSS SyntaxHighlighter 2.0: short tutorial on how to create your own syntax highlighter
CSS SyntaxHighlighter 2.0: Notes on using with TEXTAREA and PRE

Hope this helps

I work for iTrinegy. Here are my other Syntax Highlighter and Prototype blogs

3 Comments Post a comment
  1. Barun Saha
    Jul 29 2010

    Hey Joe!

    You’re great! Your solution works perfectly! I got so frustrated while trying to this thing for last few days. Thanks!

  2. Grzex
    Aug 9 2010

    Thank you very much for this post. It helped not to resign on ajax in my site.
    I’m really grateful.

  3. mehmet uluturk
    Apr 9 2011

    Thanks a lot. It works fine.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Note: HTML is allowed. Your email address will never be published.

Subscribe to comments

%d bloggers like this: