0
votes

I'd like to trigger an event once after key down and a different event only after the down arrow key has been released, like so:

$('body').keydown(function (e)
{
    if(e.keyCode==40)
    {
        //do something
    }
    $('body').keyup(function (d)
    {
        if(d.keyCode==40)
        {
            //do something else
        }
    }
}

This code only functions partially. The keydown is triggered continuously as the down arrow key is held.

I have a setInterval whose refresh rate I'm altering when I hold the arrow key. Unforunately setTimeOut isn't an option in this situation.

So my code looks something like this:

        clearInterval(interval);
        refresh = 100;
        interval();
4
Partially? So what is the part that does not work for you? - Mario S
You're currently binding a new event handler to the onkeyup event whenever a keydown event occurs. Also, can you please be a bit more specific on your problem? - Niko
What exactly do you need - there are already two different events (one for keydown, one for keyup)? - Bergi
I understand this code isn't functioning, I'm just trying to communicate what I'm trying to accomplish. - Jack Guy

4 Answers

1
votes
$('body').keydown(function (e) {
    if(e.keyCode==40) {
        //do something
    }
    return false;
})
.keyup(function(e) {
    if(e.keyCode==40) {
        //do something else
    }
    return false;
});


$('body').on('keyup', function (e) {
    if(e.keyCode==40) {
        //do something
    }
    // after first keyup set to handle next keydown only once:
    $(this).one('keydown', function(e) {
        if(e.keyCode==40) {
            //do something else
        }
    });
});

If you need exactly trigger the event and not handle as it's in your example, then you need to use $.trigger() method.

1
votes

If you want to do some action only once while the key remains pressed, simply keep track of that:

var arrowKeyDown = false;

$('body').keydown(function(e) {
    if (e.which == 40 && !arrowKeyDown) {
        arrowKeyDown = true;
        // ...
    }
});

$('body').keyup(function(e) {
    if (e.which == 40) {
        arrowKeyDown = false;
    }
});

Demo: http://jsfiddle.net/utfwQ/

0
votes
$('body').keydown(function (e)
{
    console.log('down');
}​).keyup(function(e){console.log('up')});​​​​
0
votes

If you really need to remove the keyup listener when you're done, http://jsfiddle.net/CgmCT/

document.body.addEventListener('keydown', function (e) {
    if(e.keyCode === 40){
        console.log('key 40 down');
        // key down code
        document.body.addEventListener('keyup', function listener(d){
            if(d.keyCode === 40){
                document.body.removeEventListener('keyup', listener, true);
                console.log('key 40 up');
                // key up code
            }
        }, true);
    }
}, true);​