I am using jresig's jquery hotkeys and it looks like it works for single hotkeys. The problem is I have a list of hotkeys from the db and I want to read them and assign the hotkeys dynamically. So I have a list of hotkeys and values and this is my js:
$(document).ready(function() {
var keyList = [];
$('.hotkey').each( function(){
hotkey = $(this).attr('value');
hotkey = hotkey.substring(1,hotkey.length-1);
myVal = $(this).next().attr('value');
alert("binding " + hotkey);
$(document).bind('keydown', hotkey, function() {
alert("YOU PRESSED " + hotkey);
$('.chosen-category-id').attr('value', hotkey);
$('.chosen-category-name').attr('value', myVal);
});
})
})
What happens now is that every time i press a key, it just alerts the last hotkey it bound. Is there something wrong with the logic here? I am keeping myself from copy pasting a zillion document.bind lines so I'm trying to do this dynamically.
EDIT
I refactored my code with this:
$(document).ready(function() {
var keyList = [];
var keyValues = [];
$('.hotkey').each( function(){
hotkey = $(this).attr('value');
hotkey = hotkey.substring(1,hotkey.length-1);
keyList.push(hotkey);
keyValues.push($(this).next().attr('value')) ;
})
$.each(
keyList,
function(index, key) {
$(document).bind('keydown', key, function() {
alert("O HAI YOU PRESSED " + key);
$('.chosen-category-id').attr('value', key);
$('.chosen-category-name').attr('value', keyValues[index]);
return false;
});
}
)
})
it works now but im curious as to why this works and the other does not. Does the hotkey variable keep overwriting the last iteration? Also that first code looks more efficient as it only does one loop while this second code does two.