JSFiddle - React, Tailwind, and code Playground

by nnnnnn

HTML

<div id="test"></div>

CSS

div {
    position : absolute;
    width : 20px;
    height : 20px;
    background-color : red;
}

JavaScript

var keyState = {};

window.addEventListener('keydown',function(e){
    keyState[e.keyCode || e.which] = true;
},true);

window.addEventListener('keyup',function(e){
    keyState[e.keyCode || e.which] = false;
},true);

x = 100;

function gameLoop() {
    if (keyState[37] || keyState[65]){
    x -=1;
    }

    if (keyState[39] || keyState[68]){
    x += 1;
    }
    
    document.getElementById("test").style.left = x + "px";
    
    setTimeout(gameLoop, 10);
}

gameLoop();