I need to make an image move on a web page. The code below shows how I can use JavaScript to accomplish this task:
<html>
<head>
<title>Snake</title>
<script type="text/javascript" src="snake.js"></script>
<!-- <link type="text/css" href="snake.css"> -->
</head>
<body onKeyPress="ProcessKeypress(event);">
<p><img id="snake" style="z-index: 0; left: 300px; position: absolute; top: 250px"
float=top border=0 hspace=0 src="snake.gif"></p>
</body>
But now, I want to use CSS to style the image element. However, when I modify the code as shown below, the movement functionality no longer works:
<html>
<head>
<title>Snake</title>
<script type="text/javascript" src="snake.js"></script>
<link type="text/css" href="snake.css">
</head>
<body onKeyPress="ProcessKeypress(event);">
<p><img id="snake" src="snake.gif"></p>
</body>
@CHARSET "UTF-8";
img {
z-index: 0;
left: 300px;
position: absolute;
top: 250px;
float: top;
border: 0;
hspace: 0;
}
The JavaScript code snippet provided below is what I am currently using to animate the image. Any suggestions or guidance would be greatly appreciated.
function moveObj(name, Xpix, Ypix)
{
obj = document.getElementById(name);
px = parseInt(obj.style.left) + Xpix;
py = parseInt(obj.style.top) + Ypix;
obj.style.left = px;
obj.style.top = py;
}
function ProcessKeypress(e)
{
var myObj = 'snake';
var moveBy = 10;
if(e.keyCode === 97) {
moveObj(myObj, -moveBy, 0);
}
else if(e.keyCode === 100) {
moveObj(myObj, moveBy, 0);
}
else if(e.keyCode === 115) {
moveObj(myObj, 0, moveBy);
}
else if(e.keyCode === 119) {
moveObj(myObj, 0, -moveBy);
}
}