Jonathan
Jonathan

Reputation: 2073

jQuery Keydown/Keyup only works every second time

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

Answers (3)

easywaru
easywaru

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" enter image description here

Upvotes: 1

RobF
RobF

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

M41DZ3N
M41DZ3N

Reputation: 346

use

$(document).on('keyup', function(e) {
    $('div').removeClass('bar');
    e.preventDefault();
});

e.preventDefault(); will reset the input

Upvotes: 6

Related Questions