Reveal.js lets you create dynamic presentations in an HTML file using simple markup based on the HTML5 section element (tutorial here). Reveal presentations look spiffy and have an intuitive navigation interface, even on touch devices. After publishing a presentation I created using Reveal.js (see production version at this Learn More) page, it was pointed out it lacked the webcomic feature of using a click anywhere in the background to move to the next page. A teachable moment! Enter the Reveal.js API and its addEventListener method.

Using the Reveal.js API to advance to the next page

All the Reveal.js commands are available through its simple and logicalAPI. A few typical examples:

The API we’d like called when a key is pressed is the The question is, how do we use it? An obvious answer is to hijack the jQuery .click() handler somehow, or perhaps the newer .on() handler. But no.

Using addEventListener in Reveal.js

A quick refresher on where UI constructs you may think of as Javascript come from–things like keyboard handling, user input, even the alert() method. They’re not built into Javascript. They come from the implicitly declared window object, which is provided by the browser’s runtime environment; you won’t see alert() mentioned in the Javascript language standard. Remember that code like alert('hello, world') is actually a shortcut for window.alert('hello, world').

My first instinct was to attach a click handler using the window object’s addEventListener() method, so I searched the Reveal.js source code to see how it was used, and discovered that Reveal has its own wrapper for addEventListener(). Perfect. Here’s a first shot at it.

Not quite. This prevented other keyboard functions from working, such as clicks on URLs. The key is knowing about event bubbling. Event bubbling is the process by which the user interface manager moves events higher up into the hierarchy; click on piece of text in a button and it’s ignored, for example, so it bubbles up to the button handler and gets consumed there.

We just want clicks on the background to run the function, so add the false parameter to the end of the Reaveal.addEventListener() handler. It prevents the keystroke from being consumed, so that Reveal.js still has access to it for other purposes. Thus:

Here’s all the code in context. Run the demo and see what happens when you click the background. Run an earlier version) which lacks the background click handler and try the click thing.

Here is the entire program with the addEventListenter() handler in all its glory. The new code is highlighted.