I have a web app that I’m working on that I would like the user to be able to define and trigger hotkeys dynamically. I hope someone can help me out?
I’ve created a JSFiddle HERE with the pertinent HTML.
Here’s my javascript:
// Assign Hotkey (this seems to be working)
$('input.hotkey').keydown( function(event) {
var hkey = event.keyCode;
if ( hkey == $('span#hk').text()){
alert('This key is already in use');
} else
$(this).parent().parent().prev().find('span#hk').text(hkey);
});
// Fire Hotkey (the problem might be here?)
$(document).not('input').keydown( function (event) {
var hkey = event.keyCode;
if (hkey == $('span#hk').text()){
$("span#hk:contains("+hkey+")").parent().click();
}
});
// Play Selected Track
$('#track').live('click', function () {
// Fake Function
var title = $('#title', this).text();
alert(title + ' is playing...');
});
Note: I have already used the ‘space’ and ‘left/right’ arrow keys as global hotkeys – is there a way to protect/prevent them from being assigned?
Is there a better selector to use than .not(‘input’) to prevent firing the track during input typing?
Thanks for the help!
$(document).not('input')does not find all elements that are notinputtags. It finds all the document nodes (of which there is one) that are not input elements (which is all one of them). All you’ve done is attached the handler to thedocument. Because parent elements are notified of events triggered on their descendants, allkeydownevents are handled by this function.You should make use of
event.targetinstead:The
ifstatement means the handler does not do anything if the event originated on aninputelement.