Skip to content

Instantly share code, notes, and snippets.

@nikcorg
Last active December 15, 2015 22:49
Show Gist options
  • Save nikcorg/5335316 to your computer and use it in GitHub Desktop.
Save nikcorg/5335316 to your computer and use it in GitHub Desktop.
Keyboard navigation for Fingerpori @ Turun Sanomat using (jQuery) promises
// Keyboard navigation for http://ts.fi/viihde/fingerpori/
(function ($) {
"use strict";
if (!$) {
console.error("jQuery is missing");
return;
}
var KEYS = {
ARROW_LEFT: 37,
ARROW_RIGHT: 39,
ARROW_UP: 38,
ARROW_DOWN: 40,
// Store interesting keycodes for quick lookup
VALID: [37, 39, 38, 40]
};
function identifyActor(kc) {
var actor = null;
switch (kc) {
case KEYS.ARROW_RIGHT:
actor = ".comic .comic-button-next";
break;
case KEYS.ARROW_LEFT:
actor = ".comic .comic-button-prev";
break;
case KEYS.ARROW_DOWN:
actor = "#comic-serie-container .comic-button-next";
break;
case KEYS.ARROW_UP:
actor = "#comic-serie-container .comic-button-prev";
break;
}
return actor;
}
function navigate(e) {
var actor, fetch;
if (KEYS.VALID.indexOf(e.keyCode) === -1) {
return;
}
e.preventDefault();
e.stopPropagation();
// Create actor promise
actor = $.when(identifyActor(e.keyCode)).
then(function (actor) {
return $(actor);
});
// Create fetch promise
fetch = actor.
then(function ($actor) {
return $actor.attr("href");
}).
then(function (url) {
return $.get(url);
});
// Then wait until both resolve
$.when(actor, fetch).
then(function (actor, fetch) {
return $(actor.data("ajaxUpdate")).html(fetch[0]);
}, function (err) {
console.error("error", err);
});
}
$(window).on("keydown", navigate);
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment