Using keyup to change absolute position using JavaScript -


all i'm trying move div around screen using arrow keys. newbie javascript , wrote seems should working it's not. every keyup moving div based on it's original position , not current position of div. there i'm missing?

css: #pawn { position: absolute; left: 0; top: 0; width: 50px; height: 50px; }

javascript

 function showkeycode(e) {      var pawn = document.getelementbyid("pawn");      if(e.keycode == "37") {         console.log("left");         pawn.style.left = -50+"px";     }     if(e.keycode == "38") {         console.log("up");         pawn.style.top = -50+"px";     }     if(e.keycode == "39") {         console.log("right");         pawn.style.left = +50+"px";     }     if(e.keycode == "40") {         console.log("down");         pawn.style.top = +50+"px";     } } 

html:

 <body onkeyup="showkeycode(event);">   <div id="pawn"></div>  </body> 

can shine light on this? i've been stuck hours.

the pawn.style.left properties text, you're not incrementing value @ all. assignments "set positive/negative 50+"px"; every time.

you'll need convert values integers , add new value, , set px value.

a basic demo in jquery:

$(function(){   $('body').on('keyup', function(e){     var pawn = $('#pawn');     var newleft = parseint(pawn.css('left')) + 50;     pawn.css('left',newleft+'px');   }); }); 

codepen

you can infer how add support different directions/arrow keys.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -