Moving a box in JavaScript again -- the program seems to be detecting two key presses even though I'm only pressing one
<p>I'm trying to build on the top answer <a href="http://stackoverflow.com/questions/4950575/how-to-move-a-div-with-arrow-keys">here</a> by adding "gravity" such that the box always moves down unless a key is pressed. </p>

<p>I've been fiddling for a couple of hours now and I can't figure it out. In the previous code he send two variables to the calculateNewValue function, for top and left of the css position. </p>

<p>I thought I would simply be able to break these two tests for true/false key presses out into four, and then add a +1 for when the up arrow is false, hence the box will always fall down unless you tell it not to.</p>

<p>It almost works, but the box moves down and to the right, instead of just down. And gravity doesn't work like that.</p>

<p>This must have something to do with top and left being used to move the box in two directions. But if the event handler is storing the keycode for only one key, wouldn't all the other tests return false? How can I get it to not move right?</p>

<pre><code>$(function(){

var pane = $('#pane'),
    box = $('#box'),
    maxValue = pane.width() - box.width(),
    keysPressed = {},
    distancePerIteration = 3;

function calculateNewValue(oldValue) {
    var newValue = parseInt(oldValue, 10)
                   - (keysPressed[37] ? distancePerIteration : 0)
                   - (keysPressed[38] ? distancePerIteration : 0)
                   + (keysPressed[39] ? distancePerIteration : 0)
                   + (keysPressed[40] ? distancePerIteration : 1)
    return newValue &lt; 0 ? 0 : newValue &gt; maxValue ? maxValue : newValue;
}

$(window).keydown(function(event) { keysPressed[event.which] = true; });
$(window).keyup(function(event) { keysPressed[event.which] = false; });

setInterval(function() {
    box.css({
        left: function(index ,oldValue) {
            return calculateNewValue(oldValue);
        },
        top: function(index, oldValue) {
            return calculateNewValue(oldValue);
        }   
    });
}, 20);

});
</code></pre>
