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>