I am using this code to move an element around based on keydown event:
$("body").on("keydown", function(event) {
var arrow_position = $(".down-arrow").position();
if(event.key == 's') {
$(".down-arrow").css({"top": arrow_position.top - 10});
}
if(event.key == 'w') {
$(".down-arrow").css({"top": arrow_position.top + 10});
}
if(event.key == 'a') {
$(".down-arrow").css({"left": arrow_position.left - 10});
}
if(event.key == 'd') {
$(".down-arrow").css({"left": arrow_position.left + 10});
}
});
body {
font-family: var(--font-family);
font-size: 4rem;
overflow: hidden;
position: relative;
/* width: 1920px; */
/* height: 1080px; */
}
.down-arrow {
left: 58%;
position: absolute;
bottom: 5%;
border: 1px solid red;
height: 50px;
width: 50px;
transform: rotate(170deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="down-arrow">
</div>
The element is directly inside the body.
However, the element only moves left when I press either a or d. Similarly, it only moves up when I press s or w. It also moves in increments of 20 instead of 10. What am I doing wrong?
Thanks.