I have this small snippet to change a bit of html when a user presses the Alt key, and then change it back when they release it.
$(document).keydown(function(e) {
if(e.altKey) {
$('#title').html('foo');
$(this).keyup(function(e) {
$('#title').html('bar');
});
}
});
This works fine the first time, but the 2nd time it doesn’t. The 3rd does work, 4th doesn’t etc…
Why do the key events only seem to get triggered every other key press?
Are you using this in Firefox? If so, Firefox will steal focus when you press alt, preventing the document from getting the keypress, and give it back on the next alt press. Also, you are assigning a keyup handler to the document every time you press alt, so by the 10th time, you are calling keyup 9 times. You need to separate the two:
Demo: http://jsfiddle.net/HZ5gw/
Note: in jQuery,
return falseis the same as doinge.preventDefault(),e.stopPropagation, and stopping callbacks. It looks like Chrome needspreventDefault()and firefox needsstopPropagation, soreturn falseaccomplishes both of these. You could also just call each of those instead.