jQuery Keyer 1.0
Keydown events fire at high frequencies when keys are held down.
jQuery Keyer allows you to customize your own preferred sensitivity on how keydown events are fired.
jQuery Keyer also helps you manage keydown events involving multiple keys.
HTML
<div class="demo">
<p>Demo 2</p>
<p>Click in this textbox, press any one or more keys.</p>
<p>Try holding down multiple keys.</p>
<p>The textbox below will show which keys are pressed, and for how long.</p>
<input type="text" id="DEMO_2" value="" readonly />
</div>
CSS
html, body {
line-height: 1.8em;
font-family: Arial;
font-size: 10pt;
}
div.demo {
border: 1px solid #ddd;
padding: 10px;
margin: 15px 15px 35px 15px;
}
div.demo input {
width: 80%;
}
JavaScript
/**
* Define the KeyEvent object if it does not exist
* http://mzl.la/Hw2KjT
*/
$(document).ready(function () {
$.fn.keyer = function (settings) {
var defaults = {
interval: 50,
initialDelay: 0,
keydown: $.noop,
keyup: $.noop,
fireKeydownOnMultipleHits: true
};
this.each(function (i, el) {
var state = {
event: null,
pressed: [],
timer: null,
elapsed: 0
},
options = $.extend(true, {}, defaults, settings);
var $this = $(el);
/**
* Proxy function that always runs at an interval
* and fires the "intended" keydown event when conditions are met.
*
* Note that this function is *NOT* directly fired by a keydown event
*/
function keydownProxy (event, run) {
if (state.pressed.length) {
if (run || state.elapsed > options.initialDelay) {
options.keydown.apply(this, [state.event]);
}
state.elapsed += options.interval;
}
}
/**
* Adds the pressed key into internal array
*/
function addKey (key) {
if (state.pressed.indexOf(key) == -1) {
state.pressed.push(key);
return true;
}
return false;
}
/**
* Removes the released key from internal array
*/
function removeKey (key) {
var i = state.pressed.indexOf(key);
if (i != -1) {
state.pressed.splice(i, 1);
}
if (!state.pressed.length) {
...