Moving a div on key press can be accomplished using a combination of HTML, CSS

I am currently working on an HTML game where the player can navigate around the webpage. However, I am encountering issues with getting the movement functionality to work. My goal is to have the player move when certain keys are pressed. While I was able to confirm that key presses are registered using alerts, I haven't been successful in actually moving the player div. Below is a snippet of my code:

function keyPress(){
if(window.event.keyCode == 87){
    document.getElementById("player").style.left = 10 + 'px';
}
if(window.event.keyCode == 83){
  alert("spressed")
}
if(window.event.keyCode == 65){
  alert("apressed")
}
if(window.event.keyCode == 68){
  alert("dpressed")
}
}
.player{
  background-color: black;
  height: 50px;
  width: 50px;
}
<!doctype html>

<html onkeydown="keyPress()">
  <head>
    <link rel="stylesheet" href="lib/style.css">
    <script src="lib/script.js"></script>
  </head>

  <body>
    <div class="player" id="player">
    </div>
  </body>
</html>

This task might be simple for some of you, so any assistance would be greatly appreciated. Thank you! :)

Answer №1

The main issue at hand is that the class .player does not have a position attribute assigned to it. You need to specify the position as absolute in order for it to work correctly.

position: absolute;

If you want the element's position to be relative to its containing block, use the above code. Alternatively, you can use:

position: fixed;

to set the position of the element based on the initial containing block.

Here is a working example:

function keyPress(){
if(window.event.keyCode == 87){
    document.getElementById("player").style.left = 10 + 'px';
}
if(window.event.keyCode == 83){
    document.getElementById("player").style.left = 50 + 'px';
}
if(window.event.keyCode == 65){
    document.getElementById("player").style.left = 100 + 'px';
}
if(window.event.keyCode == 68){
    document.getElementById("player").style.left = 150 + 'px';
}
}
.player{
  position: fixed;
  background-color: black;
  height: 50px;
  width: 50px;
}
<!doctype html>

<html onkeydown="keyPress()">
  <head>
    <link rel="stylesheet" href="lib/style.css">
    <script src="lib/script.js"></script>
  </head>

  <body>
    <div class="player" id="player">
    </div>
  </body>
</html>

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

Excellent Methods for Implementing a Double Click Functionality in JavaScript for Mouse

Is there a way to make the mouse double click by itself using JavaScript? I need this functionality for a Selenium project that requires testing, but unfortunately Selenium does not provide an option for double clicking. Can anyone suggest how I can achiev ...

Using CSS to Showcase Text and Images

Setting up a database for Weapons for Sale and incorporating PHP code: <?php echo '<link rel="stylesheet" href="display.css" type="text/css">'; function FindPhoto($name) { $dir_path = "http://www.chemicalzero.com/FireArms_Bis/Guns ...

Using AngularJS ng-if to dynamically show header content according to the current route

Having trouble with my Single Page Application (SPA) where the header needs to change based on the user's route location. The code I've written seems correct, but I keep getting an error: TypeError: undefined is not a function Here's what t ...

Enhancing user experience by highlighting invalid input fields with a red border using client-side HTML5 validation and Bootstrap 5.2

When reviewing the Bootstrap 5.2 validation documentation, https://getbootstrap.com/docs/5.2/forms/validation/ "It has come to our attention that the client-side custom validation styles and tooltips are not accessible at this time, as they are not ...

What is the best way to design a send button in a comment textbox to resemble the one in the Facebook app?

As a beginner in coding, I am trying to recreate the comment section of the Facebook app where the send icon is integrated into the textarea and positioned at the right end. Although I have been experimenting with some code, I am facing issues where the t ...

Accessing Data from the Wikipedia API

After receiving a JSON response with the following structure: { "batchcomplete": "", "query": { "pages": { "97646": { "pageid": 97646, "ns": 0, "title": "Die Hard", "extract": "Die Hard is a 1988 ...

Utilizing checkboxes to toggle the visibility of a div element with varying headings

By toggling a checkbox, I aim to show or hide the same div with a different heading. $('#cbxShowHide').click(function() { this.checked ? $('#block').show(1000) : $('#block').hide(1000); }); #block { display: none; bac ...

Identifying all failed http GET requests

Within my application, there is a grid that retrieves data through HTTP promises. Currently, I am able to recognize errorCallbacks - as demonstrated below: myDataPromise.then(function () { //do stuff }, function errorCallback(response) { if (r ...

Exploring the usefulness of `bind(this)` within a ReactJS constructor

I have a good understanding of the Javascript function bind. However, I'm puzzled by why in the React.js snippet below, this is being bound again to itself. Is this related to the constructor, as this in the constructor can vary depending on how it&ap ...

Exploring Vuetify Labs: leveraging slots for custom icons in VDataTable

Has anyone successfully implemented rendering an icon in a VDataTable column using slots with the latest Lab release of Vuetify3? In Vuetify Version 2.x, it was achieved like this: <template> <v-data-table :headers="headers" : ...

Excessive whitespace appearing on the right and bottom edges of the Angular application

I'm fairly new to web development, so this may be a silly question, but I really could use some help. I've created my first Angular app and noticed that there is a lot of white space on the right side of the landing page, as well as at the bottom ...

What is the best way to ensure that the radius of the circle adjusts according to the canvas element in

I've successfully drawn a circle on a canvas element, but now I need to make it responsive. How can I achieve this? I want the radius of the circle to change by a certain amount when the browser width or height changes. How do I calculate this changi ...

Guide to displaying query results separately on a single webpage

On my page, I have two distinct sections: 1) A list of regular questions; 2) A top-voted list of popular questions Both of these sections rely on calls to the same backend API, with the only difference being an additional parameter passed for the popular ...

Obtain facial rotation using Three.js

In my code, I am calculating the intersections of mouse clicks with Three.js as follows: myVector.set( (event.clientX / window.innerWidth) * 2 - 1, -(event.clientY / window.innerHeight) * 2 + 1, 0.5); myVector.unproject(myApp.camera); myRay.se ...

When users install my npm module, they are not seeing text prediction (intellisense) in their editors

I'm currently focused on developing my package @xatsuuc/startonomy. I'm encountering an issue where Intellisense is not working properly when the package is installed on the user's side. Even though the .d.ts files are visible in node_modul ...

Updating the urlTemplate property of a MapView.UrlTile component in real-time

As a newcomer to React and React Native, I am currently exploring the usage of React Native Maps. My goal is to dynamically update the urlTemplate property of a MapView.UrlTile component every second for a certain number of times. My approach involves usi ...

I am looking to split an array into smaller subarrays, each containing 5 elements, and assign a distinct class to the elements within each subarray. How can I

I have a group of "n" "li" elements that I would like to split into "x" subsets using jQuery. Each subset should contain 5 "li" elements, and I also want to assign a different class to each subset. <ul> <li>text1</li> <li>text2&l ...

Tips for establishing a connection to a SQL CE database using JavaScript within Internet Explorer

I am currently working on a Browser Plugin that involves storing data in an SQLCE Database locally. My challenge is to display this saved data on a webpage within the browser by connecting to the local database and fetching the values using JavaScript. S ...

Numerous web worker asynchronous requests are being made, but not all are coming back

Within my web worker script, I am utilizing the following code: self.addEventListener('message', function(e){ try { var xhr=new XMLHttpRequest() for(var i = 0; i < e.data.urls.length;i++){ xhr.open('GET&apos ...

What is the most efficient method for swapping out a portion of an array with a different one in Javascript?

Currently experimenting with Dygraph and have successfully integrated a reloader feature that adds high-resolution data as users zoom in on the graph. To maintain the original file boundaries, I am preserving the existing data and inserting the newly load ...