Why isn't the javascript addEventListener doing anything? -


i'm trying write script moves orange box around inside blue box using arrow keys , javascript eventlistener. when run page, nothing happens. i've tried poking around in console, isn't giving me output @ all. i'm sure i'm missing small can't life of me figure out. suggestions great!

var orange = document.getelementbyid("orange");  orange.addeventlistener("onkeydown", move, false);  function move(e);      			  e = e || window.event;           if(e.keycode == '38'){ //up      	if(parseint(orange.style.top) > '0'){      		orange.style.top = parseint(orange.style.top) - 5;      	}     } else if (e.keycode == '40'){ //down      	if(parseint(orange.style.top) < '425'){      		orange.style.top = parseint(orange.style.top) + 5;      	}     } else if (e.keycode == '37'){ //left      	if(parseint(orange.style.top) > '0'){      		orange.style.left = parseint(orange.style.left) - 5;      	}     } else if (e.keycode == '39') { //right      	if(parseint(orange.style.left) < '425') {      		orange.style.left = parseint(orange.style.left) + 5;      	}         }  }      	
#blue{      background-color: blue;      position: relative;      height: 500px;      width: 500px  }  #orange{      background-color: orange;      position: absolute;      width: 75px;      height: 75px;  };
 <div id="blue">       <div id ="orange" style="left: 30px; top:30px;"></div>   </div>      

you have couple problems:

1) event keydown not onkeydown (unless adding directly object: (e.g. orange.onkeydown)

2) top measured in pixels, not integer - need add + 'px' top changes: orange.style.top = parseint(orange.style.top) + 5 + 'px'

other notes:

  • might work better have event listener on window have focus, idk though - didn't test that.
  • e.keycode number, not string
  • as @bmceldowney mentioned, have syntax error in function declaration

working version of code: https://jsfiddle.net/kkhkl065/


Comments