Skip to content

Instantly share code, notes, and snippets.

@TexRx
Forked from karlseguin/gist:2462535
Created May 23, 2012 01:55
Show Gist options
  • Save TexRx/2772814 to your computer and use it in GitHub Desktop.
Save TexRx/2772814 to your computer and use it in GitHub Desktop.
extensions to HTMLDocument for setting up click and keypress events
//Helper extension for setting up document.on('click') and document.on('keypress') if escape...
//I think it's pretty stupid code, inspired by having eaten absolutely too much, watcha gonna do.
//usage:
// document.on('escape', hide);
// document.on('click', hide);
(function(){
var events = {'escape': [], 'click': [], 'enter': []};
HTMLDocument.prototype.on = function(e, callback) {
events[e].push(callback);
if (events[e].length > 1) { return; }
if (e == 'escape') { return setupOnKeyPress('escape', 27); }
if (e == 'enter') { return setupOnKeyPress('enter', 13); }
if (e == 'click') { return setupOnClick(); }
}
function setupOnKeyPress(name, code) {
$(document).on('keydown', function(e) {
if (e.keyCode != code) { return }
fireEvents(name);
});
return true;
}
function setupOnClick() {
$(document).on('click', function() {
fireEvents('click');
});
return true;
}
function fireEvents(name) {
for(var i = 0; i < events[name].length; ++i) {
events[name][i]();
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment