OdeToCode IC Logo

Build Your Own Slide Presenter: Part 2

Tuesday, February 14, 2012

The slide show project currently only shows one slide. I know a number of people who can talk for 75 minutes using one slide, but fortunately they've all retired from university life and taken their overhead projectors with them.

Today's speakers need to show at least one Internet meme infested slide every 30 seconds to keep an audience alert and happy. We must find a way to allow a presenter to move through slides with a keystroke, or the swipe of the finger. We'll look at touch later, and work on just the keystrokes.

One way to process keys is to use a giant switch statement.

switch(event.keyCode) {
    case 39: // that's the right arrow
    case 40: // down arrow ...
    // etc...

Let's try something different. We'll add a variable to our p5 object that maps key codes to objects with action function. The name property is just here for readability.

var keys = {
    39: { name: "rightArrow", action: moveForward },
    40: { name: "downArrow",  action: moveForward },
    34: { name: "pageDown",   action: moveForward },
    32: { name: "space",      action: moveForward },
    37: { name: "leftArrow",  action: moveBackward },
    38: { name: "upArrow",    action: moveBackward },
    33: { name: "pageUp",     action: moveBackward },
    36: { name: "home",       action: moveFirst },
    35: { name: "end",        action: moveLast }

Then, once we've wired up the keydown event in the start method..

var start = function () {
    $(window).bind("keydown", keyDown);

.. we can handle a key down event without an ugly switch.

var keyDown = function (event) {
    var handler = keys[event.keyCode];
    if (handler) {

Next we'll add a brute force implementation of the actions.

var moveForward = function () {
    var current = $("section.current");
    var next = current.next("section");
    if (next.length) {

var moveBackward = function () {
    var current = $("section.current");
    var prev = current.prev("section");
    if (prev.length) {

var moveFirst = function () {

var moveLast = function () {

I already hate the code. The number of string literals drives me crazy. We'll need to schedule another post just for refactoring and cleanup. Everyone cleans up their JavaScript code, right?

At this point we have a semi-working slide show! Only ... it's ugly and scrolls downward because the section elements are in the normal flow of the document and have a height despite being invisible. We will fix the aesthetics in the next post.

For all the code, see github.