Moving Image Element to a position with only Javascript - Here's my code.

568 views Asked by At

-- CSS

#Char { 
position:absolute; 
top: 500px; 
left: 500px; 
height: 80px; 
width: 80px;
}

-- HTML

<!DOCTYPE html> 
<html> 
<head>
<link rel="stylesheet" type="text/css" href="TopDown.css">
</head>
<body> 
<img id = "Char" src = "GunMan.jpg">
<script>
var Char = document.getElementById('Char');
document.addEventListener("onkeydown",UpMove(Eve)); 
UpMove(Eve) { 
if (Eve.keyCode == 38) { 
Char.style.top = "300px";
}
</script> 
</body> 
</html> 

Moving Image Element to a position with only Javascript - Here's my code. I can't move the image for some reason to 300px. also tell me if theirs any bad habits placed within this code...

3

There are 3 answers

0
Leo Bauza On

You are missing the closing curly bracket for your UpMove function causing a javascript error.

Uncaught SyntaxError: Unexpected token {

You are also missing the keyword "function" for your UpMove function.

The event is "keydown" not "onkeydown"

I've edited this a couple of times, so rather than keep doing that here is a fiddle that works:

https://jsfiddle.net/ys5wcp9c/3/

0
Özgür Ersil On

try like that

var Char = document.getElementById('Char');

document.onkeydown = UpMove;

function UpMove(Eve) { 
    if (Eve.keyCode == 38) {   
        Char.style.top = "300px";
    }
}
0
Krystian Jankowski On

There was few issues with your code. You should use "keydown" instead of "onkeydown".

Try this script

var Char = document.getElementById('Char');
document.addEventListener ("keydown",UpMove); 

function UpMove(e) { 
  console.log(e)
  if (e.keyCode == 38) { 
    Char.style.top = "300px";
  }
}