Alex Hill
Alex Hill

Reputation: 711

Moving a div dynamically with keystrokes vanilla javascript

I am building a simple Pirates clone in the browser, and using regular javascript with no libraries in an attempt to learn the basics. I am trying to move a relative positioned div that is my game sprite, within an absolute positioned div that is the game board. I have all of the code up to the point of actually moving the div, I just cant find the command to change the relative positioning of a div.

Here is what I have:

function move(e){
    var x=e.keyCode;
    var keychar=String.fromCharCode(x);
    if (x === "a") {
       // What goes here?
    }
};

Upvotes: 0

Views: 552

Answers (5)

bfavaretto
bfavaretto

Reputation: 71918

First, your inner div should have position: absolute, not relative. The outer one could have either. Then it's just a matter of setting style.top and style.left on every keystroke:

function move(e){
    var x=e.keyCode;
    var keychar=String.fromCharCode(x).toLowerCase();
    var div = document.getElementById('mydiv');
    if (x === "a") {
        var currentLeft = parseInt(div.style.left, 10);
        // to move left:
        div.style.left = (currentLeft-5) + 'px';
    }
};

That should work, but your sprite may not move as smoothly as you expect. In that case, you'll probably need an animation loop, and a keystroke buffer.

Upvotes: 1

Seth Flowers
Seth Flowers

Reputation: 9190

var div = document.getElementById("divId");

if(x == "a"){        
    div.position.left = (parseInt(div.style.left) - 10) + "px";
}
else if(x == "d"){
    div.position.left = (parseInt(div.style.left) + 10) + "px";
}

// similar code for other keys with div.style.top

Upvotes: 0

Anoop
Anoop

Reputation: 23208

You can change style.left and style.top

var d = document.getElementById("idselector");
d.style.left = "30px";
d.style.top = "40px";

Upvotes: 0

Vinod Vishwanath
Vinod Vishwanath

Reputation: 5891

Change(increase or decrease) the divElement.style.left value in pixels.

Upvotes: 1

Sampson
Sampson

Reputation: 268344

You should be able to move it by modifying el.style.left and el.style.top where el is a reference to your positioned DIV.

Upvotes: 1

Related Questions