I've seen lots of people ask similar questions here, but none of them seem to work for me. I have an img, with the id 'character'. I want it to move left on left click and right on right click. This is the code I have:
var bound = window.innerWidth;
function left(id) {
document.getElementById(id).style.left.match(/^([0-9]+)/);
var current = RegExp.$1;
if(current <=bound){
document.getElementById(id).style.left = current - 0 + 'px';
}
else{
document.getElementById(id).style.left = current - 5 + 'px';
}
}
function right(id) {
document.getElementById(id).style.left.match(/^([0-9]+)/);
var current = RegExp.$1;
if(current >= (bound - 5){
document.getElementById(id).style.left = current + 0 + 'px';
}
else{
document.getElementById(id).style.left = current + 1 + 'px';
}
}
document.onkeyup = KeyCheck;
function KeyCheck() {
var KeyID = event.keyCode;
switch(KeyID)
{
case 39:
right('character');
break;
case 37:
left('character');
break;
}
}
I don't know if I should fix this code, or if there is something simpler. If you have a simpler way of doing this, please let me know.
Your steps are different in the left and right function. use one variable to avoid that. Example
Why not use jQuery?
Here is a demo of it in action