Over a million developers have joined DZone.

Auto-escaping code blocks in Reveal.js

DZone's Guide to

Auto-escaping code blocks in Reveal.js

· Web Dev Zone ·
Free Resource

Jumpstart your Angular applications with Indigo.Design, a unified platform for visual design, UX prototyping, code generation, and app development.

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.

	<h1>Testing Code</h1>
var x = 1;
var y = 2;
var z = "Do people even read my code samples?";
var zz = "I mean really, are *you* reading this?";

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:

document.addEventListener("DOMContentLoaded", init, false);

function init() {
	console.log("Run my init, yo!");

	var cblocks = document.querySelectorAll("pre code");
	if(cblocks.length) {
		for(var i=0, len=cblocks.length; i<len; i++) {
			var dom = cblocks[i];
			var html = dom.innerHTML;
			html = html.replace(/</g,"<").replace(/>/g,">");
			dom.innerHTML = html;

	// Full list of configuration options available here:
	// https://github.com/hakimel/reveal.js#configuration
		controls: true,
		progress: true,
		history: true,
		center: true,
  //i cut some stuff out here to save space in the code block


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.


Take a look at an Indigo.Design sample application to learn more about how apps are created with design to code software.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}