I am new to javascript and I am trying to start a very simple project which is to display a controllable div that can be moved around using a,w,s,d keys on keyboard. I am currently having problem on how to move around the div because I do not know what attribute to change.
divBar = null;
function detectKey() {
//97 = a
//115 = s
//100 = d
//119 = w
if (event.charCode == 97) {
//a
alert(divBar.position);
}
if (event.charCode == 115) {
//s
}
if (event.charCode == 100) {
//d
}
if (event.charCode == 119) {
//w
}
}
function createDiv() {
divBar = document.createElement("div");
divBar.id = "divBar";
divBar.style.border = "solid 1px #AAAAAA";
divBar.style.backgroundColor = "black";
divBar.style.top = 400;
divBar.style.height = "10px";
divBar.style.width = "100px";
divBar.style.position = "absolute";
document.body.appendChild(divBar);
document.addEventListener("keypress", detectKey, false);
}
I am not sure to put in that condition statement. so that the div will move to the left, right, up and down.
If it’s absolutely positioned (which it appears to be), then you change divbar.style.top and divbar.style.left to move it around.
Here’s a working example: http://jsfiddle.net/jfriend00/rRbZz/.