Search code examples
javascriptfor-loopwhile-loopkeypress

How do I change a value only when a key is pressed down?


I have tried to make a code where a ball only moves when I press the arrow keys and when I let go it stops, but it continues to move. How can I fix this?

This is the part of the code that I have written:

document.onkeydown = function tast (e) {
    if (e.keyCode == 39) {  // høyre
        høyre = 1;  
    } else {
        høyre = 0;
        console.log("ikke høyre")
    }
    if (e.keyCode == 37) {  // venstre
        venstre = 1;  
    } else {
        venstre = 0;
    }
    if (e.keyCode == 38) {  // opp 
        opp = 1; 
    } else {
        opp = 0;
    }
    if (e.keyCode == 40) {  // ned
        ned = 1;              
    } else {
        ned = 0;
    }
}

if (venstre == 1){
    kuler[0].x -= 4;
}
if (høyre == 1){
    kuler[0].x += 4;;
}
if (opp == 1){
    kuler[0].y -= 4;
}
if (ned == 1){
    kuler[0].y += 4;
}

Solution

  • Other then setting your values to 0 on else. Use a onkeyup event handler. Then for onkeypress set your values to 1. And onkeyup set them to 0:

    document.onkeydown = function tast (e) {
        if (e.keyCode == 39) høyre = 1;  
        if (e.keyCode == 37) venstre = 1;  
        if (e.keyCode == 38) opp = 1; 
        if (e.keyCode == 40) ned = 1;              
    }
    
    document.onkeyup = function tast2 (e) {
        if (e.keyCode == 39) høyre = 0;  
        if (e.keyCode == 37) venstre = 0;  
        if (e.keyCode == 38) opp = 0; 
        if (e.keyCode == 40) ned = 0;              
    }