Home > Blockchain >  How to move div onkeypress HTML CSS Javascript
How to move div onkeypress HTML CSS Javascript

Time:10-18

I am currently trying to make an html game where the player can move around the web page but I cannot get the movement to work. I want the player to move on key press. I got the key press to work, I tested it with an alert, but I cant get it to move the div. Here's my code,

function keyPress(){
if(window.event.keyCode == 87){
    document.getElementById("player").style.left = 10   'px';
}
if(window.event.keyCode == 83){
  alert("spressed")
}
if(window.event.keyCode == 65){
  alert("apressed")
}
if(window.event.keyCode == 68){
  alert("dpressed")
}
}
.player{
  background-color: black;
  height: 50px;
  width: 50px;
}
<!doctype html>

<html onkeydown="keyPress()">
  <head>
    <link rel="stylesheet" href="lib/style.css">
    <script src="lib/script.js"></script>
  </head>

  <body>
    <div  id="player">
    </div>
  </body>
</html>

This is probably easy for some of you so I appreciate the help. Thanks : )

CodePudding user response:

The issue here is that the .player class has no position attribute, you must define the position as absolute like that

position: absolute;

if you want to set the position of the element in relation to its containing block, or use

position: fixed;

to set the position of the element in relation to the initial containing block.

Working snippet

function keyPress(){
if(window.event.keyCode == 87){
    document.getElementById("player").style.left = 10   'px';
}
if(window.event.keyCode == 83){
    document.getElementById("player").style.left = 50   'px';
}
if(window.event.keyCode == 65){
    document.getElementById("player").style.left = 100   'px';
}
if(window.event.keyCode == 68){
    document.getElementById("player").style.left = 150   'px';
}
}
.player{
  position: fixed;
  background-color: black;
  height: 50px;
  width: 50px;
}
<!doctype html>

<html onkeydown="keyPress()">
  <head>
    <link rel="stylesheet" href="lib/style.css">
    <script src="lib/script.js"></script>
  </head>

  <body>
    <div  id="player">
    </div>
  </body>
</html>

  • Related