It looks like key-press can only be executed on a focus element? I don\'t fully buy into that, there has to be a way to execute a key-press event similar to a click event?
So you are only going to be able to listen to the keypress in whichever element that you have the listener set on (or its children). And the keypress event is only going to fire if the element is focused. So I think the best solution for you would be to set focus
on the element you are hovering over, then you can listen for the keypress
, or better yet, listen to keydown
because it behaves in a more standard way cross browser.
Here is a working JSFiddle demonstrating this technique: http://jsfiddle.net/DfjF2/2/
Only certain form elements accept focus
. You can add contenteditable
or tabindex
attributes to the element, and that should allow pretty much any element to receive focus, but then the keydown
event won't actually get fired! This is a browser specific issue. In my experience, a <span>
will cause keydown
and keyup
events to be fired in every browser I have tested (Chrome, Firefox, IE, Safari, Android browser, Silk). So in the jsfiddle I added a span inside the target element, put focus
on that, and added the keydown
event listener to it.
So if you added an empty <span>
into your view, your code could look something like this:
var PlayerView = Backbone.View.extend({
tagName: 'div',
events: {
'click .points, .assists, span.rebounds, span.steals':'addStat',
'mouseenter': 'enter',
'mouseleave': 'leave',
'keydown': 'keyAction'
},
enter: function() {
this.$el.addClass('hover');
var span = this.$el.find('span');
span.attr('tabindex', '1').attr('contenteditable', 'true');
span.focus();
},
leave: function() {
this.$el.removeClass('hover');
var span = this.$el.find('span');
span.removeAttr('contenteditable').removeAttr('tabindex');
span.blur();
},
keyAction: function(e) {
var code = e.keyCode || e.which;
if(code == 65) {
alert('add assist')
}
}
});