Modifying dp.SyntaxHighligher to use PRE tags

I’ve been using the excellent dp.SyntaxHighlighter on my blog for a while now, to apply code highlighting to blog entries. This simply involves wrapping the code sample in a textare tag with the css class specifying the language, and the entry automatically gets parsed by a javascript function which executes at the end of each page.

Works great, until the entry is viewed in a [web-based] RSS reader, where the textarea remains a textarea, and not only doesn’t have syntax highlighting, but is in a small textarea box with horizontal and vertical scrollbars. Ideally, we need a solution where we can use something like pre tags, which would result in the code being highlighted when viewed on the original website, and not highlighted but still readable when viewed through an RSS reader.

Fortunately, this is very easy to do. Simply modify your shCore.js file, and do a search for propertyName. By default, the value is ‘value’, but to make it work with pre tags, it should be changed to ‘innerText’. On pages with code, you should use <pre id=’code’ class=’c#’>…code…</pre>.

The only problem with this, is that if you’ve been using dp.SyntaxHighlighter already, and have old blog entries where you’ve used textareas, then these will no longer work. Hence, what we need to do is apply a conditional check to ensure that we use the correct property to retrieve the code.

Above the line highlighter.Highlight(element[propertyName]);, add the following line: var propertyName = (element.type == ‘textarea’) ? ‘value’ : ‘innerText’;. This will use the value property to retrieve the code to highlight if the element is a textarea, otherwise ‘innerText’ will be used (for pre tags).

This entry was posted in Uncategorized by Mun. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *