How can I move an image element on the x-axis at keypress with Javascript?

In my Django project, I have a "sprite" which is an image element in the HTML template. I want to make a small interactive game on the page when clicked on "A" key, the image will move on the x-axis. How can I achieve that with JavaScript? I tried to change the offsetLeft value using .offsetLeft and the x position value by updating the .style attribute but couldn't manage it both ways.

contact.html:

{% load static %}
{% block script %}
    <script src="{% static 'potbs/contact.js' %}"></script>
{% endblock %}

{% block body %}
<div class="col">
    <img src="media/images/phone.png" alt="phone" class="rounded floar-start">
    <img src="media/images/stick.png" class="rounded float-end" id="sprite" alt="..." style="margin-top:100px;">
    <img src="media/images/wasd.png"  class="rounded float-end" id="wasd" alt="..." style="margin-top:100px;display: none;">
    <button class="btn btn-primary float-end" id="start">Start</button>
</div>
{% endblock %}

contact.js:

document.addEventListener("DOMContentLoaded", function(){

    const button = document.getElementById("start");
    const wasd = document.getElementById("wasd");
    const sprite = document.getElementById("sprite");

    
    button.onclick = function(){
        button.style.display = "none";
        wasd.style.display = "block"
        document.addEventListener("keypress",function(event){
            if(event.key == "a"){
                wasd.style.display = "none";
                sprite.offsetLeft = sprite.offsetLeft + 10;
            }
        });
    };
})

I think the easiest way to position elements relative to a container would be to set the position for the container as relative and for the child as absolute, then use the left and top style properties to position the element as you wish. So in your case, you could do something like this -

<!DOCTYPE html>
<html lang="en">

<head>
  <script>
    function limitInPercent(value) {
      if (value < 0) return 0;
      if (value > 100) return 100;
      return value;
    }
    const SCALE = 10;
    document.addEventListener("DOMContentLoaded", function() {

      const sprite = document.getElementById("sprite");


      document.addEventListener("keypress", function(event) {
        const top = sprite.style.top || 0;
        const left = sprite.style.left || 0;
        if (event.key == "a") {
          sprite.style.left = limitInPercent(parseInt(left) - SCALE) + "%";
        } else if (event.key == "d") {
          sprite.style.left = limitInPercent(parseInt(left) + SCALE) + "%";
        } else if (event.key == "w") {
          sprite.style.top = limitInPercent(parseInt(top) - SCALE) + "%";
        } else if (event.key == "s") {
          sprite.style.top = limitInPercent(parseInt(top) + SCALE) + "%";
        }
      });
    })
  </script>

</head>

<body>
  <div class="col">
    <div id="sprite">x</div>
  </div>
</body>

</html>
Back to Top