Reputation: 2073
I have keyup/down events binded to the document. The Keydown will only fires every second time, without me knowing why. I tried many suggestions given on similar SO-Questions, but none of them works.
My Javascript:
$(document).on('keyup', function() {
$('div').removeClass('bar');
});
$(document).on('keydown', function(e) {
if(e.altKey) {
$('div').addClass('bar'); // only every second hit will add the class
}
});
This should point out the issue: http://jsfiddle.net/6yxt53m9/1/
Upvotes: 0
Views: 2788
Reputation: 1153
Try this.
$(document).on('keydown', function(e) {
e.preventDefault();
if(e.altKey) {
$('div').addClass('bar'); // only every second hit will add the class
}
});
The reason is alt key occurs focus moving to button of "customize and control google chorome"
Upvotes: 1
Reputation: 2818
You need to add return false;
to the key press functions:
$(document).on('keyup', function() {
$('div').removeClass('bar');
return false;
});
$(document).on('keydown', function(e) {
if(e.altKey) {
$('div').addClass('bar');
}
return false;
});
Updated fiddle.
Upvotes: 7
Reputation: 346
use
$(document).on('keyup', function(e) {
$('div').removeClass('bar');
e.preventDefault();
});
e.preventDefault(); will reset the input
Upvotes: 6