JavaScript Continue keydown event even when an additional button is pressed

One thought added to everyone else's good ideas:

Separate your user input from your drawing.

Keyboarding:

If you’re having problems with KeyboardJS, check out Keydrown: http://jeremyckahn.github.io/keydrown/

Don’t do any drawing when capturing keys…just capture the user’s input of which direction they want the circle to go.

Set up an “direction” variable to hold how many times the user has pressed [left] or [right]:

var direction=0;  

When [left] is pressed:

direction--; 

When [right] is pressed:

direction++;

Direction is a net number. So if the user holds down the left key for 20 strokes and the right key for 15 strokes, direction will be -5 ( -20 + 15 ).

Set up an “altitude” variable to hold how many times the user has pressed [space]:

var altitude=0;

When [space] is pressed:

altitude-=10;

Altitude is a net number also.

Drawing:

Do all your drawing in a separate animation loop. Rather than using javascript’s setInterval, use the new and improved way of creating an imation loop -- requestAnimationFrame.

// set the starting circle positions 

var currentX=canvas.width;
var currentY=canvas.height-r;

function animate(){

    // even as we're executing this current animation loop
    // request another loop for next time

    requestAnimationFrame(animate);

    // change the currentX position by the accumulated direction

    currentX+=direction;
    direction=0;

    // change the currentY position by the accumulated altitude

    currentY+=altitude;
    altitude=0;

    // draw the circle at its current position

    cc();

    circle(currentX,currentY,r);

    // apply gravity to the circle
    // to make it fall if its in the air

    if(currentY<canvas.height-r){
        currentY++;
    }

}

Good Luck with your project!

Answer:1

What the problem is, is that if you press another key after pressing the first key, it will trigger that event, and stop triggering the other keydown event. This can be seen in this simplified example:

addEventListener('keydown',function(e) {console.log(e.keyCode, e.keyIdentifier)});

If you run that script, and then press left and then up, it will first show 37 Left a bunch of times, and then it'll show 32 U+0020 once and stop logging the left keydowns.

This is simply how the browser (and most other basic programs too) work. You can try doing the same thing in for example notepad, if you press the A key first, and then press space, it'll stop adding more As. This also means that you can't rely on key events (or key event libraries) to do this for you.

What you could do though, is make a global object that holds all keys that are pressed. For example:

window.KeysDown = {
    37: false, //Left
    39: false, //Right
    38: false, //Up
    40: false, //Down
    32: false, //Space
};

addEventListener('keydown', function(e) {
     var keyCode = e.keyCode||e.charCode||e.which;
     if (keyCode == 32 && !window.KeysDown[keyCode])
         onSpace();//This will only run when the spacebar is first pressed down.
     if (window.KeysDown.hasOwnProperty(keyCode))
         window.KeysDown[keyCode] = true;
});
addEventListener('keyup', function(e) {
     var keyCode = e.keyCode||e.charCode||e.which;
     if (window.KeysDown.hasOwnProperty(keyCode)) window.KeysDown[keyCode] = false;
});

var interval = setInterval(function() {
    for (var i in window.KeysDown) {
        if (window.KeysDown[i]) switch (i+'') {
            case '37': onLeft(); break;
            //case '38': window.KeysDown[i] && onUp(); break;
            case '39': onRight(); break;
            //case '40': window.KeysDown[i] && onDown(); break;
        }
    }
}, 50);

The syntax window.KeysDown[i] && onLeft() causes the onLeft function only to run if window.KeysDown[i] is true. I hope this solution works for you.

EDIT: I've changed the code to the working one. I've also made a JSFiddle that demonstrates this. The problem in my previous code was that apparently a switch doesn't handle integer values well, so I needed to convert i to a string.

EDIT: I've also added an extra part to the script that makes the onSpace function only run when the spacebar is first pressed down, and so that it won't run again until the spacebar is released and pressed again. I've also updated my JSFiddle to include these changes.

Answer:2

I am unable to append values into the _summary class or any other. I believe its a really simple syntax error I am making. I have been trying different syntax's for the past day, with no luck. I am ...

I am unable to append values into the _summary class or any other. I believe its a really simple syntax error I am making. I have been trying different syntax's for the past day, with no luck. I am ...

  1. append event jquery
  2. append event
  3. append event listener
  4. append event javascript
  5. append event listener jquery
  6. append event handler jquery
  7. append event onclick
  8. append event handler c#

Here is my d3.js code , from here on right click i am calling the function contextmenu // Display the tiles for each bucket. var tile = svg.selectAll(".tile") .data(buckets) .enter().append("...

Here is my d3.js code , from here on right click i am calling the function contextmenu // Display the tiles for each bucket. var tile = svg.selectAll(".tile") .data(buckets) .enter().append("...

  1. right click opens link in new tab
  2. right click opens windows installer
  3. right click opens new window
  4. right click opens on left
  5. right click opens properties
  6. right click opens link
  7. right click opens window
  8. right click menu opens on left side
  9. right click automatically opens
  10. autocad right click opens help
  11. firefox right click opens link
  12. shift right click opens powershell
  13. double right click opens properties
  14. right click menu opens slow
  15. chrome right click opens new tab
  16. right click mouse opens
  17. double click opens right click menu

I am developing inside of a Google Chrome Extension. In this environment, I have the ability to inject JavaScript into third-party websites after requesting the appropriate permissions. As such, I am ...

I am developing inside of a Google Chrome Extension. In this environment, I have the ability to inject JavaScript into third-party websites after requesting the appropriate permissions. As such, I am ...

I've having trouble parsing integers or even text from <strong> elements on a page. What I want to do is parse the number of followers from a Twitter profile, like this one. Using Google dev ...

I've having trouble parsing integers or even text from <strong> elements on a page. What I want to do is parse the number of followers from a Twitter profile, like this one. Using Google dev ...

  1. parseint text value