my file:
index.html
client
css
style.css
js
javascript.js
index.html:
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>blablabla</title>
<link rel="stylesheet" type="text/css" href="client/css/style.css">
<script type="text/javascript" src="client/js/javascript.js"></script>
</head>
<body>
<div id="container">
<div id="guy"></div>
</div>
</body>
</html>
javascript.js
var guy=document.getElementById('guy');
var container=document.getElementById('container');
var guyLeft=0;
function anim(e){
if(e.keyCode==39){
guyLeft +=2;
guy.style.left = guyLeft + 'px';
}
if(e.keyCode==37){
guyLeft -=2;
guy.style.left = guyLeft + 'px';
}
}
document.onkeydown =anim;
style.css
#container{
height:400px;
width:600px;
outline:1px solid black;
position: relative;
}
#guy{
position: absolute;
height:50px;
width:50px;
outline:1px solid black;
background-color:red;
left:0;
}
1)So guys pls help.. I just want to move object left and right .. when i put that code between in index.html it works but in seperate javascript.js class doesn't work. Thx for help.
1) You have to load the JavaScript at the bottom of the page.
<!doctype html>
<html>
<head>
<meta charset="utf-8"/>
<title>blablabla</title>
<link rel="stylesheet" type="text/css" href="client/css/style.css">
</head>
<body>
<div id="container">
<div id="guy"></div>
</div>
<script type="text/javascript" src="client/js/javascript.js"></script>
</body>
</html>
2) Move up and down:
var guy = document.getElementById('guy');
var container = document.getElementById('container');
var guyLeft = 0;
var guyTop = 0;
function anim(e){
if(e.keyCode==39){
guyLeft +=2;
guy.style.left = guyLeft + 'px';
}
if(e.keyCode==37){
guyLeft -=2;
guy.style.left = guyLeft + 'px';
}
// UP
if(e.keyCode==38) {
guyTop -=2;
guy.style.top = guyTop + 'px';
}
// DOWN
if(e.keyCode==40) {
guyTop +=2;
guy.style.top = guyTop + 'px';
}
}
document.onkeydown = anim;
You should use the console if you want to catch bugs and errors in JavaScript.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments