Question

I'm trying to move a div element using left position. To do this i squared a div and got his element id in javascript to give it +-3pixels depending on ley strokes left and right. I've added console logs to know this stuff is working and everything is flowing accordingly, the only problem is ... IT ISNT working !!! I don't need a new code, just to understand what i'm doing wrong

The html:

<html>
    <body>
        <div id="container"> 
            <div id="guy"> </div>
        </div>
    </body>
    <script src="script.js"></script>
    <style>
        #container{background-color: teal;width: 500px;height: 500px;margin: auto; position: absolute;}
        #guy{background-color: black;width: 30px;height: 30px;}
    </style>
</html>     

the javascript file:

var theMan = document.getElementById('guy');
theMan.style.position = "absolute";
xLeft = 0;
function move(e) {
    var e = e.keyCode;
    switch(e) {
        case 37:
            if (xLeft == 0) {
                console.log("Already reached the left edged");
            } else {
                console.log("Pressed LEFT");
                xLeft -= 3;
                moveGuy();
            }
            break;
        case 39:
            if (xLeft == 500) {
                console.log("Already reached the right edged");
            } else {
                console.log("Pressed RIGHT");
                xLeft += 3;
                moveGuy();
                console.log(xLeft);
            }
            break;
        default:
            console.log("Use the cursor keys idiot!");
            break;
    }
}

function moveGuy() {
    theMan.style.left = xLeft + " px";
    console.log("moving");
}

document.onkeydown = move;
Was it helpful?

Solution

You have a space too many, replace

theMan.style.left = xLeft + " px";
//                          ^^ no space here

with

theMan.style.left = xLeft + "px";

FIDDLE

I'll be changing my nick to "EagleEyes"

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top