0

I am new to Html/Javascript and tried to move an image with arrow keys. It worked, however when the style.top of the image goes under a certain number (It seems 100px), it hops to style.top = 425px, which is supposed to only happen if style.top >= 450. Here is my code:

var keys = [];


 window.addEventListener("keydown", function(e){
  keys[e.keyCode] = true;
 }, false);
 window.addEventListener("keyup", function(e){
  delete keys[e.keyCode]
 }, false);



function init(){

var link = document.getElementById("link");
 setTimeout(function(){
  loop();
 }, 1)
}


function update(){
 if(keys[38]){
  link.style.top = parseInt(link.style.top) - 3 + 'px'
  if(link.style.top <= 000 + 'px'){
   link.style.top = 000;
  }
   console.log(link.style.top)
 }
 if(keys[40]) {
  link.style.top = parseInt(link.style.top) + 3 + 'px'
  if(link.style.top >= 425 + 'px') {
   link.style.top = 425;
  }
   console.log(link.style.top)

 }
 if(keys[37]) {
  link.style.left = parseInt(link.style.left) - 3 + 'px'

 }
 if(keys[39]) {
  link.style.left = parseInt(link.style.left) + 3 + 'px'

 }
}




function loop(){
 setInterval(function(){
  update();
 }, 1000/60)
}
<html>
<head>
 <title>Game</title>
 <link rel="stylesheet" type="text/css" href="styles.css">
 <script type="text/javascript" src = "script.js"></script>
</head>
<body onload = "init()">

<!-- Images for the page -->

<img id = "link" src = "http://i.imgur.com/clcuHKG.jpg" style = "position: absolute; top:250; left:500;" height = "200" width = "200">

</body>
</html>

1 Answers1

0

You are doing calculations with strings. Try to avoid that! Strings do not behave like numbers.

For example, you compare the top value, which is, e.g. '99px' to the value '425px'. The string compare routine thinks 99px is bigger, because the ASCII value of the first character, 9, is larger than the ASCII value of 4.

So what you need to do is use the numerical value. for instance with parseInt(link.style.top). Then you're comparing the numbers 99 and 425 and all will be well.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150