Performing horizontal movement on a div element

Hey there! I've created a mini game and I'm currently facing an issue. I want my "player" div to move left and right within the confines of the "game" div, but I seem to be stuck. Can anyone lend a helping hand? I have a feeling that the error lies within the JavaScript file... Also, will the "gun" div move along with the "player" div if it moves?

let modifier = 50;
let player = document.getElementById('player');
window.addEventListener('keydown', (event) => {
  const {
    style
  } = player;
  switch (event.key) {
    case 'ArrowRight':
      style.left = `${parseInt(style.left) - modifier}px`;
      break;
    case 'ArrowLeft':
      style.left = `${parseInt(style.left) + modifier}px`;
      break;
  }
});
body {
  margin: 0;
  padding: 0;
  background-color: mediumblue;
  height: 800px;
  overflow: hidden;
}

p {
  font-size: 48pt;
  color: black;
  font-family: fantasy;
  font-weight: bold;
  position: relative;
  left: 300px;
  top: -50px;
}

.game {
  width: 800px;
  height: 500px;
  position: center;
  border: 14px solid darkblue;
  border-radius: 5px;
  margin-left: 300px;
  margin-top: -100px;
  background-color: black;
}

#player {
  height: 20px;
  width: 40px;
  background-color: firebrick;
  border-radius: 2px;
  position: relative;
  top: 470px;
  left: 400px;
}

#gun {
  position: relative;
  height: 40px;
  width: 10px;
  background-color: firebrick;
  top: -20px;
  left: 15px;
  border-radius: 2px;
}

#bullet {
  position: relative;
  background-color: darkorange;
  width: 8px;
  height: 20px;
  top: 0;
  left: 1px;
  animation: shoot 0.7s linear;
}

@keyframes shoot {
  0% {
    top: 0px;
  }
  100% {
    top: -470px;
  }
}
<p>Galaxy Invaders</p>
<div class="game">
  <div id="player">
    <div id="gun">
      <div id="bullet"></div>
    </div>
  </div>
  <div id="enemy"></div>
</div>
<script src="js.js"></script>

Answer №1

If you want to achieve this, utilize the getComputedStyle method: https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

let adjustment = 50;
let character = document.getElementById('player');

window.addEventListener('keydown', (event) => {
  switch (event.key) {
    case 'ArrowRight':
      character.style.left = (parseInt(getComputedStyle(character).left) + adjustment) + "px";
      break;
    case 'ArrowLeft':
      character.style.left = (parseInt(getComputedStyle(character).left) - adjustment) + "px";
      break;
  }
});
body {
  margin: 0;
  padding: 0;
  background-color: mediumblue;
  height: 800px;
  overflow: hidden;
}

p {
  font-size: 48pt;
  color: black;
  font-family: fantasy;
  font-weight: bold;
  position: relative;
  left: 300px;
  top: -50px;
}

.game {
  width: 800px;
  height: 500px;
  position: center;
  border: 14px solid darkblue;
  border-radius: 5px;
  margin-left: 300px;
  margin-top: -100px;
  background-color: black;
}

#player {
  height: 20px;
  width: 40px;
  background-color: firebrick;
  border-radius: 2px;
  position: relative;
  top: 470px;
  left: 400px;
}

#gun {
  position: relative;
  height: 40px;
  width: 10px;
  background-color: firebrick;
  top: -20px;
  left: 15px;
  border-radius: 2px;
}

#bullet {
  position: relative;
  background-color: darkorange;
  width: 8px;
  height: 20px;
  top: 0;
  left: 1px;
  animation: shoot 0.7s linear;
}

@keyframes shoot {
  0% {
    top: 0px;
  }
  100% {
    top: -470px;
  }
}
<p>Galaxy Invaders</p>
<div class="game">
  <div id="player">
    <div id="gun">
      <div id="bullet"></div>
    </div>
  </div>
  <div id="enemy"></div>
</div>

Answer №2

When using JavaScript to retrieve CSS property values of HTML elements through either .style or getComputedStyle(), the values will be returned as strings such as 10px for a rule like div { left: 10px }, including unit types based on the CSS property.

To utilize numeric values in calculations, you must first remove the unit type from these strings and then apply parseInt method:

parseInt(style.left.replace('px', ''))

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

What is the correct way to align text in jsPDF?

I'm currently encountering an issue with the jsPDF library. Although PDF generation works fine, I am struggling to justify text properly. The align: 'justify' attribute seems to function the same as align: 'left', and setting a spe ...

The chart is failing to update with the data it obtained through Jquery

Scenario: I want to populate a chart using data fetched by Jquery. $.getJSON("/dashboard/", function(data, status) { var test_data=data console.log(test_data) chart.data.datasets[0].data=test_data; ...

Ways to switch out error message for an error landing page

I am currently displaying error text when something goes wrong, but I would like to enhance the user experience by redirecting to a well-designed error page instead. Can anyone provide guidance on how to achieve this? Below is my existing code for display ...

The proxy is unable to access the method within the subclass

Issues are arising as I attempt to utilize a Proxy. The structure of my class is as follows: export class Builder { public doSomething(...args: (string | number | Raw | Object)[]): this { // Do stuff return this } } export class M ...

Is there a way to locate the source or URL linked to a button on a form or webpage?

Currently, I am extracting data feeds from a webpage by clicking a button that is similar to the 'Login' button displayed on the following link: However, this button acts as a 'Download' request that initiates the download of a csv rep ...

The equation of jquery plus ie7 results in an undefined value

I am experiencing a strange issue in IE7 with a jQuery script. This problem seems to only occur in IE7. In summary, when I check the console window, it shows that jQuery is not defined - even though I have loaded jQuery (version 1.7.1) from my disk and can ...

Clicking on the title link will open the content in an iframe, but the image

Having trouble with a previous post but I've created a codepen to illustrate the issue. Hoping someone can help me out! Check out the codepen here: "https://codepen.io/Lossmann/pen/GRrXyQY" ...

Preventing Javascript array elements from being overwritten: Best practices

My challenge lies with the addToClients() function, which is designed to add a new value to the clients array whenever a button is pressed. The issue I am facing is that each time I press submit, the previous element in the array gets replaced by the new o ...

What is the best method for styling arrays displayed by React in version 15 using CSS?

React v15 has made a change where elements of arrays in JSX are now rendered as <!--react-text:some_id-->text<!--/react-text--> instead of spans. I've searched for a solution but haven't been able to figure out how to apply CSS styles ...

Different kinds of garbage collection operations in NodeJS

When utilizing the perf_hooks module in NodeJS, we have access to information regarding garbage collection. This can be achieved by using PerformanceObserver, which is triggered with each garbage collect event. const obs = new perf_hooks.Performanc ...

Is there a way to implement this toolbar in Ionic Angular?

https://i.sstatic.net/sGd1o.png I am looking to replicate the toolbar shown in the image above using Ionic. As a beginner in Ionic development, I am finding it challenging to translate the design into code. I attempted to use a grid layout, but the varyin ...

The suspense fallback function seems to be missing in NextJS 13

I'm in the process of creating an application to demonstrate the functionality of Suspense in Nextjs 13. However, I'm encountering an issue where the Suspense fallback is not appearing during loading. Below is the code for page.js import React, ...

php Use cURL and the DOM to extract content with specified CSS styling

Unclear in the title, I want to copy all content from a specific div on an existing webpage (not owned by me). The code successfully extracts the content. Extractor code: // Get Data $curl_handle=curl_init(); curl_setopt($c ...

Tips to store Google fonts in the assets directory

I've included this link in my styles.scss @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap'); While it works locally, the API fails on production or is blocked. How can I host it within my p ...

Incorporating a way to automatically initiate a GET request following a POST request in React can effortlessly display a new

In my App component, I display a list of items and have a ModalForm where users can add new items. However, after adding a new item, I currently have to reload the page in order to see it in the list. I am looking for a way to automatically trigger a GET ...

Retrieve the parent element of the selected tag within an iframe

I have an embed iframe that displays an HTML page. Now I am trying to retrieve the class of the parent item that was clicked. <iframe src="//example.com" id="frame" ></iframe> This is the CSS styling for the iframe: #frame{ width:380px; he ...

Tips for defining CSS styles for the background color of <td> elements within a sitemap

I am facing a similar issue to the one discussed in this thread Possible to fill a table cell with a bg color?. The challenge I am encountering is related to applying CSS styles to the td tags within a sitemap structure. (Although it functions correctly ...

Using Router.back in Next.js triggers a complete page refresh

I am working on a page called pages/conversations/[id].tsx, and here is the code: import Router, { useRouter } from 'next/router' export default function ConversationPage() { const router = useRouter() ... return ( <View ...

Addressing Problems with Horizontal Navigation Layout

I am working on creating a horizontal navigation bar that resembles link [1], but it currently looks more like link [2]. How can I adjust my code to achieve the desired look? The wrapper's width is set at 80em and each link should be 155x76px. Wheneve ...

div consistently positioned above fixed element

My goal is straightforward - I have a fixed div at the bottom of my page that always needs to be visible. Inside this div, there are two sub-divs; one small div should always be on top, and the other should be scrollable. The issue lies with the small div ...