Auto-escaping code blocks in Reveal.js

Warning - this falls into the "Cool, but may not be a good idea category." I'm a huge fan of the Reveal.js framework for HTML-based presentations and I've already posted a few of my utilities/tips/etc for making it work better (or at least better for me). One issue I've run into a few times lately is escaping HTML for code slides. Reveal.js has great support for code coloring (color coding?). Here's a quick screen shot of an example:

In general this works simple enough. Here is how a typical code slide would look.

But if you want to include HTML in your slide then you run into a problem. As you might expect, your HTML will be rendered as, well, HTML, not source code. Typically this isn't a huge deal. Code samples are short and if you type fast, you can replace < and > in a few minutes, but after doing this a few times, and preparing to do some slides focused on HTML5 development, I thought there might be a cooler way.

By default, Reveal.js initializes itself immediately. I modified the code to do this after the DOMContentLoaded event and did some hacking:

As you can see, I simply make use of querySelectorAll to find all of my code blocks. (I could make that selector a bit more precise.) I then simply grab the HTML, escape the < and > characters, and then update the innerHTML property.

Voila!

Like This?

If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can also subscribe to the email feed to get notified of new posts.