Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't keyup() and keydown() play nicely together?

Tags:

jquery

I can't get the jQuery keyup and keydown events to work together. See this jsFiddle: http://jsfiddle.net/CXkam/1/

Code here too for ease:

$(document).keyup(function (event) {
    alert('Keyup');
});
$(document).keypress(function(e) {
    alert('Keypress: ' + String.fromCharCode(e.which));
});
$(document).keydown(function(e) {
    alert('Keydown: ' + String.fromCharCode(e.which));
});

If you comment out the keypress() and keydown() handlers, then the keyup() alert fires.

But if you don't, then keyup() never fires.

Why not?

Thanks!

like image 882
AP257 Avatar asked Dec 16 '22 17:12

AP257


1 Answers

The .keyup and .keypress events won't fire if you release the key while the dialogue box is up because the keyup message is sent to the dialogue box, which, for reasons beyond my very limited understanding of things, is not considered part of the document. What you can do, if you want to see it "work," is hold a key down (let's go with T!), hit spacebar to dismiss the dialogue box, and then release the T key. The .keyup message will then be sent to the document and processed as intended.

If you get rid of the .keydown and .keypress functions -- or the alerts within them -- then .keyup will work just fine.

like image 159
TimFoolery Avatar answered Dec 29 '22 00:12

TimFoolery