0

I'm quite new to programming as a whole and extremely new to jquery. I'm trying to make it so every time I press the W key, my cube moves upward. I can make it grow in width with the 'width("+=__")' command, but I don't want it to do that. Is there something like that width command but instead of width it changes positioning? if not, is there a simple way I can make this work? Here's what i've got right now. Instead of changing width, I want to change the positioning somehow.

    document.addEventListener('keypress', function(event){
       if (event.key === 'w') {
       document.getElementById('player').style.left = $('#player').width("+=50");
        }
    });
sbgib
  • 5,580
  • 3
  • 19
  • 26
  • Welcome to SO, and programming! A quick search turned up quite a few duplicates which answer your question, have you seen them? https://stackoverflow.com/questions/4950575/how-to-move-a-div-with-arrow-keys, https://stackoverflow.com/questions/7298507/move-element-with-keypress-multiple, https://stackoverflow.com/questions/24963796/using-jquery-keydown-to-move-box-around, https://stackoverflow.com/questions/52293082/keep-moving-an-element-when-one-key-is-pressed-jquery, https://stackoverflow.com/questions/5589239/use-jquery-to-move-dom-elements-position-across-the-screen-from-a-keypress – Don't Panic Feb 28 '21 at 08:26
  • 1
    Does this answer your question? [how to move a div with arrow keys](https://stackoverflow.com/questions/4950575/how-to-move-a-div-with-arrow-keys) – Don't Panic Feb 28 '21 at 08:26

1 Answers1

1

Try using absolute positioning on the element, then changing the top property:

document.addEventListener('keypress', function(event) {
  console.log()
  if (event.key === 'w') {
    $('#player').css("top", parseInt($('#player').css("top")) - 50 + "px");
  }
});
#player {
  position:absolute;
  top:150px;
  height:50px;
  width:50px;
  background-color:blue;
  transition: top 0.25s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Click on this snippet, then presss "W" key to move up</p>
<div id="player"></div>
sbgib
  • 5,580
  • 3
  • 19
  • 26