1

I'm trying to get a box to move when I press the arrow keys. I found this solution and tried to copy it in, but it still doesn't work (the top answer by Sime Vidas).

My Jquery file is definitely in the same folder, and everything else is just copied and pasted from the solution (which works in the JSFiddle demo). So I suppose it's not the HTML, CSS or JavaScript that's the problem but I've made some mistake putting it all together.

The box appears, but doesn't move. Why isn't it working?

<!doctype html>
<html>
<head>
<style>
#pane {
    position:relative;
    width:300px; height:300px;
    border:2px solid red;
}  

#box {
    position:absolute; top:140px; left:140px;
    width:20px; height:20px;          
    background-color:black;
}
</style>

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript">
var pane = $('#pane'),
    box = $('#box'),
    maxValue = pane.width() - box.width(),
    keysPressed = {},
    distancePerIteration = 3;

function calculateNewValue(oldValue, keyCode1, keyCode2) {
    var newValue = parseInt(oldValue, 10)
                   - (keysPressed[keyCode1] ? distancePerIteration : 0)
                   + (keysPressed[keyCode2] ? distancePerIteration : 0);
       return newValue < 0 ? 0 : newValue > 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, 37, 39);
        },
        top: function(index, oldValue) {
            return calculateNewValue(oldValue, 38, 40);
        }
    });
}, 20);

</script>

</head>

<body>

<div id="pane">
    <div id="box"></div>
</div>

</body>

</html>
Community
  • 1
  • 1
FlyingLizard
  • 2,541
  • 4
  • 13
  • 10
  • 2
    You are trying to access `#pane` and `#box` before they exist. Please read http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element and the jQuery tutorial: http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery. – Felix Kling Jan 31 '13 at 16:13

1 Answers1

2

Your code is running before the element exists.

Put the code inside document.ready:

$(function(){

    // code goes here

});
James Montagne
  • 73,502
  • 13
  • 107
  • 127