I'm currently attempting to create a dynamic object using code, but it doesn't seem to be functioning as expected. I'm curious about what might be causing the issue

I am brand new to exploring JavaScript, HTML, and CSS. I've gone through my code several times but can't quite pinpoint what's causing it not to function properly. While there are no apparent errors being returned, the expected behavior is not occurring. My goal is to have a square displayed on the screen that moves when the WASD keys are pressed. Although the square appears on the screen, nothing happens when pressing WASD. It seems like the solution should be straightforward, yet I'm struggling to find it.

<!DOCTYPE HTML>
<html>
<head>
</head>
<body onkeypress="move(event)">
  <style>
  #block {
    width: 50px;
    height: 50px;
    background-color: #555;
    margin-top: 0px;
    margin-left: 0px;
  }
  </style>
  <div id="block"class="block"></div>
  <script>
  var blockX = 0;
  var blockY = 0;
  var keyPressed = 0;
  function move(event) {
    keyPressed = event.keyCode;
    if (keyPressed === 87 || keyPressed === 83) {
      moveY();
    }
    else if (keyPressed === 65 || keyPressed === 68) {
      moveX();
    }
  }
  function moveX() {
    if (keyPressed === 65) {
      blockX -= 3;
      document.getElementById("block").style.marginLeft = blockX + "px";
    }
    else if (keyPressed === 68) {
      blockX += 3;
      document.getElementById("block").style.marginLeft = blockX + "px";
    }
  }
  function moveY() {
    if (keyPressed === 87) {
      blockY += 3;
      document.getElementById("block").style.marginTop = blockY + "px";
    }
    else if (keyPressed === 83) {
      blockY -= 3;
      document.getElementById("block").style.marginTop = blockY + "px";
    }
  }
  </script>
</body>
</html>

Answer №1

To properly compare the keyPressed variable, you can do so by checking if it equals 87 or 83 like this:

(keyPressed === 87 || keyPressed === 83)

If you want to listen for a keydown event and handle movements, you can use the following function:

document.addEventListener("keydown", function(event) {
  move(event)
});

var blockX = 0;
var blockY = 0;
var keyPressed = 0;

function move(event) {
  keyPressed = event.keyCode;
  if (keyPressed === 87 || keyPressed === 83) {
    moveY();
  } else if (keyPressed === 65 || keyPressed === 68) {
    moveX();
  }
}

function moveX() {
  if (keyPressed === 65) {
    blockX -= 3;
    document.getElementById("block").style.marginLeft = blockX + "px"
  } else if (keyPressed === 68) {
    blockX += 3
    document.getElementById("block").style.marginLeft = blockX + "px"
  }
}

function moveY() {
  if (keyPressed === 87) {
    blockY += 3;
    document.getElementById("block").style.marginTop = blockY + "px"
  } else if (keyPressed === 83) {
    blockY -= 3;
    document.getElementById("block").style.marginTop = blockY + "px"
  }
}
#block {
  width: 50px;
  height: 50px;
  background-color: #555;
  margin-top: 0px;
  margin-left: 0px;
}
<div id="block" class="block"></div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering a 422 Unprocessable Entity error when the search bar in the frontend is empty - What is the best way to handle

My frontend setup includes a search bar with an input field By combining HTMX and FastAPI, I am able to dynamically fetch user information from a static list of dictionaries. I aim for dynamic results that update as I type, and the fetching of user infor ...

What is the best way to ensure text starts on a new line when paragraphs and images are floating and aligned?

Does anyone have a clearer title idea? Feel free to edit. To better illustrate my point, I've created a jsfiddle. I am working with a simple layout of text and images. My goal is to make the second text and image appear on a new row just below the f ...

Is there a way to locate and delete an image element with a broken hyperlink?

My website is currently hosted on Wordpress, and I've noticed that there is an issue with a broken image link on my site. I'm not sure when this occurred, but it seems to only be affecting the post section of my site. https://i.sstatic.net/iarDU ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Exploring Nested Routes and Queries in Vue JS

As a beginner in Vue, I have been exploring a demo project and struggling with understanding how routes with query parameters function. The documentation suggests using router.push({ path: 'register', query: { plan: 'private' }}) to gen ...

Is there a PHP equivalent of a jQuery-style interface available?

Is there a PHP library available that offers a jQuery-style interface for working with HTML/XML files, particularly using jQuery-style selectors? I am interested in performing tasks like the following examples (purely hypothetical): foreach (j("div > ...

Ensure that all checkboxes are only selected within a single table

I have a challenge with selecting all check boxes in multiple tables when the header check box is selected. I am attempting to achieve this using jQuery without needing to parse or pass in the table id. Currently, when I select one header check box, all th ...

Collaborating on a single instance across several processes

I have a messaging bot in my project, where the connection is established using a class instance. class MessagingBot { public bot; constructor() { this.bot = new TelegramBot(); } } export default MessagingBot; In another file, I create an inst ...

Using Ajax to dynamically load page content into a div based on a selection made in a

How can I dynamically load content into a div using Ajax based on the selection made in a dropdown menu? For example, I have a select box with two options: test.HTML and test1.HTML. Below that, there is a div where I want to display the content from eithe ...

Step by step guide to building an exclusive form input field in HTML that allows only a single response

Is there a way in HTML to set up a text input or password input on a <form> that requires a specific value, such as "apples"? The form should only submit if the person entering their information types "apples" into the designated input field. ...

Tips for center-aligning layouts in Angular Material

I am struggling with the Angular Material flex layout, so I took this directly from the Angular Material website. Based on the documentation for layout container, items are arranged in a row with a max-height of 100% and max-width matching the width of th ...

Conceal an element within the initial row of the table

Below is the table structure: <table id="mytable"> <tr> <td>name</td> <td> <a id="button1" class="button">link</a> </td> </tr> <tr> <td>name2</td> ...

React's Dynamic Table fails to rerender when updated values are placed in the same row and under the same header

Here is the table generated by my functional component: <table class="table"> {/* Consonant Table */} <tr> <th colSpan="2">---</th> {headersPOA. ...

Remove duplicate JSON records in JavaScript by comparing and filtering based on identical attributes

Looking to remove duplicates from a JSON object [{id:1,name:a, cat:1},{id:1, name:a, cat:2},{id:2, name:b, cat:8}] I want to keep only the first occurrence of each duplicated id [{id:1,name:a, cat:1},{id:2, name:b, cat:8}] ...

The operation to assign a value to property 'two' cannot be completed as it is currently undefined

I'm facing an issue with the code below and cannot figure out why I am encountering the error message. I have ensured that each object contains a value, so why is there a reference to 'undefined'? Cannot set property 'two' of unde ...

The Formik form is not being populated with data from the API

While working on a functional component in ReactJS, I created a simple form using Formik. The input fields in my form are supposed to fetch data from an API when the component mounts. To achieve this, I utilized fetch and useEffect. However, after fetching ...

Send a substantial item for display using Express Layout

Utilizing Express layouts to render my webpage upon accessing a specific route: The current project I am developing is an admin panel designed for editing a substantial table of data (imagine a website dedicated to managing thousands of product entries, fo ...

Checkbox ensemble computes total score

I am currently working on a project that involves multiple checkbox groups, with each group containing 3 checkboxes labeled as (1, X, 2). My goal is to assign a value of 100% to each group, distributed evenly among the checkboxes within it. The distributio ...

In CSS, when text within a tab div lacks spaces, it triggers a horizontal scrolling effect

My special css style for the div: .message-body { background: #5181a2; padding: 8px 5px; text-align: justify; } I aim to display this particular text inside the div similar to how 'hello hello' appears on the line above. ...

Problem with the operation of SetInterval/ClearInterval loop

While I am aware that this question has been addressed previously, none of the solutions provided seemed to resolve my specific issue. The problem lies within my timer function which, upon invocation, is supposed to utilize setInterval to run every second ...