Syntax Highlighting with Javascript
If you were curious enough to dig around the source code of yesterday’s CSS tutorial, you may have noticed a couple of classes that didn’t appear to be doing anything:
<pre><code class="css">h1 {
color: navy;
border-bottom: 1px solid black;
}
</code></pre>
<pre><code class="html">...
<head>
<style type="text/css">
h1 {
color: blue;
}
...
</style>
...
</code></pre>
I added the classes in the hope that they would be useful some time in the future. This afternoon, the Internet connection in the University library stopped working so I decided to take the time to play with an idea I’ve been tossing around for a few weeks. The result: Javascript Syntax Highlighting. The concept is pretty simple—it grabs the code samples with css or html as the class, then uses regular expressions (along with some crafty callback functions) to add <span> elements to specific bits of code to allow them to be highlighted. It works in Firebird / Mozilla but fails pitifully in IE 5, which appears not to support callbacks from the string.replace() function. I haven’t tried it in IE 6 yet.
Unfortunately, it relies on the non-standards compliant innerHTML property which causes it not to work in Mozilla in XML mode, so I can’t deploy it on my blog at the moment. Due to the way the regular expressions work I’m not entirely sure how I can rectify this using standard DOM methods, so I’m leaving it as it is for the moment.
kusor - 19th May 2003 17:25 - #
There is a bug actually in MSIE6.0 instead of leaving the code like it is. MSIE6.0 stretches it.
Too bad, I thought we could all blame Bill again, but Opera 7.11 does exactly the same. Firebird (0.6) get it right however.
Anne van Kesteren - 19th May 2003 18:16 - #
hlb - 19th May 2003 18:21 - #
Martijn - 19th May 2003 23:24 - #
Just thought you might like to know the one I started in the library is now finished.
It's basically the same as yours.
Andrew Hayward - 20th May 2003 04:52 - #
I saw you where looking for a DOM method. Maybe replaceChild is something you might need?
Anne van Kesteren - 20th May 2003 07:15 - #
Steven Garrity - 1st June 2003 17:14 - #
test - 5th October 2003 22:23 - #
Martijn - 16th February 2004 14:53 - #
Eric - 13th May 2004 01:00 - #
Eddy - 5th October 2004 19:37 - #
Eddy - 5th October 2004 19:38 - #
Eddy - 12th October 2004 20:29 - #
Cok - 15th March 2005 11:09 - #
Karl - 17th May 2005 18:00 - #
Eddy: very nice...
Daniel Glazman - 12th October 2005 08:52 - #
aboutedit - 8th February 2006 14:06 - #