I would like to move a div with my arrow keys using jQuery. So right, left, down and up.
Found a demo of what I want to accomplish here
I would like to be ab
I can't see your demo, but here's a simple "move the box 1px in the direction of the arrow keys" example:
CSS:
#wrapper {
background-color: gray;
height:200px;
width: 200px;
position:absolute;
}
#mover {
background-color: white;
border: 1px solid red;
height:20px;
width: 20px;
position:relative;
}
Markup:
JS (using jQuery):
$("#wrapper").keydown(function(event) {
var $mover = $("#mover");
//if nothing else will move "mover", then track the
//position instead of recalculating it every time:
// var moverPos = $mover.position();
// var left = moverPos.left;
// var top = moverPos.top;
var addTop = function(diff) {
$mover.css("top", ($mover.position().top + diff) + "px");
//if using tracked position:
// top += diff;
// $mover.css("top", top) + "px");
};
var addLeft = function(diff) {
$mover.css("left", ($mover.position().left + diff) + "px");
//if using tracked position:
// left += diff;
// $mover.css("left", left) + "px");
};
switch(event.keyCode) {
case 37: //left
addLeft(-1); break;
case 38: //up
addTop(-1); break;
case 39: //right
addLeft(1); break;
case 40: //down
addTop(1); break;
}
});
This is just an example, you may want to add bounds checking, larger movements, smoother animation, number pad support or any number of other things to it, but it should get you started.