javascript - how to move a div with arrow keys -
i move div arrow keys using jquery. right, left, down , up.
found demo of want accomplish here
i able move div around in div.
how can done?
html:
<div id="pane"> <div id="box"></div> </div>
css:
#pane { position:relative; width:300px; height:300px; border:2px solid red; } #box { position:absolute; top:140px; left:140px; width:20px; height:20px; background-color:black; }
javascript:
var pane = $('#pane'), box = $('#box'), w = pane.width() - box.width(), d = {}, x = 3; function newv(v,a,b) { var n = parseint(v, 10) - (d[a] ? x : 0) + (d[b] ? x : 0); return n < 0 ? 0 : n > w ? w : n; } $(window).keydown(function(e) { d[e.which] = true; }); $(window).keyup(function(e) { d[e.which] = false; }); setinterval(function() { box.css({ left: function(i,v) { return newv(v, 37, 39); }, top: function(i,v) { return newv(v, 38, 40); } }); }, 20);
variable explanations:
w
- maximal left/top value box can have (to stay within bounds)
x
- distance (in px) box moves in each interval
d
- object stores information on key being pressed. instance, while user holds down left arrow key, d['37']
true
. otherwise it's false
. btw, 37
key-code left arrow key , value stored in e.which
property of event object. d
object being updated on each keydown
, keyup
event.
an setinterval executed every 20ms, updates left , top css properties of box element. new values calculated via newv
function.
the newv
function calculate new left/top value based on a) old value v
, b) d
object.
the expression n < 0 ? 0 : n > w ? w : n
ensures new value in permitted bounds (which 0 w
). if n < 0, 0 returned. if n > w, w returned.
live demo: http://jsfiddle.net/simevidas/bdmnx/1299/
update: code has same functionality original code above. difference used more meaningful names variables , arguments. can see, looks awful - original version better. :p
var pane = $('#pane'), box = $('#box'), maxvalue = pane.width() - box.width(), keyspressed = {}, distanceperiteration = 3; function calculatenewvalue(oldvalue, keycode1, keycode2) { var newvalue = parseint(oldvalue, 10) - (keyspressed[keycode1] ? distanceperiteration : 0) + (keyspressed[keycode2] ? distanceperiteration : 0); return newvalue < 0 ? 0 : newvalue > maxvalue ? maxvalue : newvalue; } $(window).keydown(function(event) { keyspressed[event.which] = true; }); $(window).keyup(function(event) { keyspressed[event.which] = false; }); setinterval(function() { box.css({ left: function(index ,oldvalue) { return calculatenewvalue(oldvalue, 37, 39); }, top: function(index, oldvalue) { return calculatenewvalue(oldvalue, 38, 40); } }); }, 20);
Comments
Post a Comment