Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keyup not firing when keydown opens an alert

I have two event handlers, one for keydown and one for keyup. The keydown event handler triggers an alert message, but this prevents the keyup event from firing.

You can see a very simple example here: http://jsfiddle.net/boblauer/jaGwT/ When the keydown opens an alert, the keyup is not fired, but when an alert is not opened, the keyup is fired. Here's the code from the jsfiddle:

var i = 0;
window.addEventListener('keydown', function(e) {
    if (i++ % 2) alert('down');
    console.log('down');
});

window.addEventListener('keyup', function(e) {
    alert('up');
    console.log('up');
});

I have a library that supports listening to multiple key combinations (such as 'd + f'), so when a key is pressed, I need to add it to a list of keys that are currently pressed, and when a key is released, I need to remove it from said list. The problem I'm running to is, if I want an alert to show when d + f are pressed at the same time, my code to remove those keys from the 'currently pressed' list never fires, because my keyup handler is never called.

I can't think of a good work around to this problem. Any ideas?

like image 399
Bob Lauer Avatar asked Nov 27 '12 21:11

Bob Lauer


People also ask

How do I trigger Keydown event?

HTML and CSS layout: In the given layout, when an input is made in the field, the keyCode value will be logged in the box. The events related to keypresses are as follows : keydown: This event is triggered when a key is pressed down. keypress: This event is triggered when a key is pressed.

What is the difference between Keyup and Keydown?

The keydown event is triggered first when user presses a key. The keyup event is triggered last when user releases a key.

Does Keydown work on mobile?

1 Answer. Show activity on this post. keydown should work, but you could use the input event which seems to have undesired effects on Android mobile...

What does the Keydown the key do?

The keydown event is fired when a key is pressed. Unlike the keypress event, the keydown event is fired for all keys, regardless of whether they produce a character value. The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered.


1 Answers

The alert prevents the event from happening. What you could do instead is trigger this function manually, because it happens anyways.

var keyupfunction = function(e){
    alert('up');
    console.log('up');
}

window.addEventListener('keyup', keyupfunction);

window.addEventListener('keydown', function(e) {
    if (i++ % 2) alert('down');
    console.log('down');
    keyupfunction(e);
});

But really, you shouldn't be using alerts. It prevents these events, but who knows what else it might break. Use something custom instead.

like image 167
Rene Pot Avatar answered Oct 18 '22 15:10

Rene Pot