Skip to content

Instantly share code, notes, and snippets.

@henriquegogo
Created August 8, 2011 17:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save henriquegogo/1132197 to your computer and use it in GitHub Desktop.
Save henriquegogo/1132197 to your computer and use it in GitHub Desktop.
HTML navigation with keyboard
(function ($) {
var keyNames = {
alt: 18, backspace: 8, capslock: 20, ctrl: 17, 'delete': 46,
down: 40, end: 35, enter: 13, esc: 27, home: 36, insert: 45,
left: 37, menu: 93, numlock: 144, numpad_add: 107, numpad_decimal: 110,
numpad_divide: 111, numpad_enter: 108, numpad_multiply: 106,
numpad_subtract: 109, pagedown: 34, pageup: 33, pause: 19, right: 39,
scrolllock: 145, shift: 16, space: 32, tab: 9, up: 38, windows: 91
};
var navegableItems = function () {
return $('a:visible, :input:visible, [tabindex]:visible', $(this).parents('.navegable')).filter(function () {
if (!$(this).parents('a:visible, [tabindex]:visible').length) return true;
});
};
$.fn.keypower = function (keyPressed, callback) {
var behaviour = function (e) {
var eventKey = e.which;
var target = e.target;
if ((keyNames[keyPressed] || keyPressed) === eventKey) {
if (callback) return callback.call(target);
else e.stopPropagation();
};
};
if (!keyPressed && !callback) keysinit.call(this);
$(this).unbind('keydown.' + keyPressed);
$(this).bind('keydown.' + keyPressed, behaviour);
return this;
};
var keysinit = function () {
$(this).keypower('up', function () {
$(this).neighbors(navegableItems.call(this)).previous.focus();
return false;
}).keypower('down', function () {
$(this).neighbors(navegableItems.call(this)).next.focus();
return false;
}).keypower('enter', function () {
if ($(this).is(":input:not(:submit):not(:button)")) {
$(this).neighbors(navegableItems.call(this)).next.focus().select();
return false;
}
});
};
})(jQuery);
$.fn.neighbors = function (navegableItems) {
var index = $.inArray(this.get(0), navegableItems);
var previous = navegableItems.eq(index - 1);
var next = (navegableItems.length <= index + 1) ?
navegableItems.eq(0) :
navegableItems.eq(index + 1);
return { previous: previous, next: next };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment