JSFiddle - React, Tailwind, and code Playground
by darcyclarke
HTML
<script src="https://raw.github.com/jeresig/jquery.hotkeys/master/jquery.hotkeys.js"></script>
<div id="user" class="object"></div>
CSS
.object {
display: block;
top: 0;
left: 0;
position: absolute;
-webkit-transition: all 0.25s;
}
#user {
background: red;
width: 10px;
height: 10px;
}
JavaScript
// Movement
var object = $('#user');
var speed = 10;
var moves = ['left','right','up','down','up+left','up+right','down+left','down+right'];
var x = parseInt(object.css('left'));
var y = parseInt(object.css('top'));
for(var i=0;i<moves.length;i++){
(function(move){
$(document).bind('keydown', move, function(e){
if(move.indexOf('left') >= 0){
x = x - speed;
}
if(move.indexOf('right') >= 0){
x = x + speed;
}
if(move.indexOf('up') >= 0){
y = y - speed;
}
if(move.indexOf('down') >= 0){
y = y + speed;
}
console.log(x, y);
object.css({left:x,top:y});
});
})(moves[i]);
}