jayShepard jayShepard - 1 year ago 133
Javascript Question

Why isn't the javascript addEventListener doing anything?

I'm trying to write a script that moves the orange box around inside the blue box using the arrow keys and Javascript eventlistener. When I run the page, nothing happens. I've tried poking around in the console, but it isn't giving me any output at all. I'm sure I'm missing something small but I can't for the life of me figure it out. Any suggestions would be great!

background-color: blue;
position: relative;
height: 500px;
width: 500px
background-color: orange;
position: absolute;
width: 75px;
height: 75px;

<div id="blue">
<div id ="orange" style="left: 30px; top:30px;"></div>

<script type="text/javascript">
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;

Answer Source

You have a couple problems:

1) The event is keydown not onkeydown (unless you are adding directly to the object: (e.g. orange.onkeydown)

2) Top is measured in pixels, not just an integer - you need to add + 'px' to your top changes: orange.style.top = parseInt(orange.style.top) + 5 + 'px'

Other notes:

  • Might work better to have the event listener on window as it will have focus, idk though - didn't test that.
  • e.keyCode is a Number, not a String
  • as @bmceldowney mentioned, you have a syntax error in your function declaration

Working version of your code: https://jsfiddle.net/kkhkL065/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download