AlgoDan
AlgoDan

Reputation: 71

How to trigger onkeydown after onkeyup?

I implemented the following:

var map = {};
document.onkeydown = document.onkeyup = function(e){
    e = e || event;
    map[e.keyCode] = e.type == 'keydown';

    if(map[38] && map[37]){ // UP + LEFT
        console.log('Up Left');
    }
    else if(map[38] && map[39]){ // UP + RIGHT
        console.log('Up Right');
    }
    else if(map[38]){ // UP
        console.log('Up');
    }
    else if(map[40]){ // DOWN
        console.log('Down');
    }
    else if(map[37]){ // LEFT
        console.log('Left');
    }
    else if(map[39]){ // RIGHT
        console.log('Right');
    }
}

If I now press the up button on my keyboard, then my console will repeatedly log "up". While I am holding the up button and start also pressing the left button, my console starts repeatedly logging "up left".

Now I release the left button and my console logs only once "up" but does not log it repeatedly anymore.

How can I achieve this?

I tried to find an answer here on StackOverflow. But I only found the solution that it only logs "up" once after I release the left button.

Can anyone help or at least give a hint please?

Upvotes: 0

Views: 67

Answers (1)

Facundo Larrosa
Facundo Larrosa

Reputation: 3389

Now I release the left button and my console logs only once "up" but does not log it repeatedly anymore.

This is the default behavior for handling key events even on common text editors as explained on this answer.

How can I achieve this?

If by this question you mean how can you continue printing "up" while UP key is pressed you will have to change your approach.

One possible approach could be by holding the state of the pressed keys on your map field and output the state repetitively in a short interval. For example, try with this code instead:

var map = {};
document.onkeydown = document.onkeyup = function(e){
    map[e.keyCode] = e.type == 'keydown';
}

logKeyState = function(){
    if(map[38] && map[37]){ // UP + LEFT
        console.log('Up Left');
    }
    else if(map[38] && map[39]){ // UP + RIGHT
        console.log('Up Right');
    }
    else if(map[38]){ // UP
        console.log('Up');
    }
    else if(map[40]){ // DOWN
        console.log('Down');
    }
    else if(map[37]){ // LEFT
        console.log('Left');
    }
    else if(map[39]){ // RIGHT
        console.log('Right');
    }
    setTimeout(logKeyState,50);
}
//Start logging  
logKeyState();

Upvotes: 0

Related Questions