js The correct value is not being set to the div's style.top

function gamestart(){
    var gr;
    var gr = true;
    console.log(gr==true);
    if(gr == true){
        console.log("we have activated pointer key detection dear Mr.ketsebaot")
        document.onkeydown = checkk;
    }

}

function checkk(e){
    console.log(e.keyCode)
    if(e.keyCode == 38){
        if(document.getElementById('player-one').getBoundingClientRect().top < 503){
            e.preventDefault(); 
            var vertical = document.getElementById('player-one').getBoundingClientRect().top;
            document.getElementById("player-one").style.top = vertical - 0.5 + "px";
            console.log(vertical)
        }
        else{
            e.preventDefault(); 
        }
        
    }
    if(e.keyCode == 40){
        e.preventDefault(); 
        var verticalb = document.getElementById('player-one').getBoundingClientRect().top;
        var newv;
        var newv = verticalb+0.5
        console.log("new top value: "+newv)
        document.getElementById("player-one").style.top = newv +"px";
    }
}
.player-one{
    position: relative;
    top: 50px;
    left: 10px;
    width: 25px;
    height: 65px;
    background-color: aliceblue;
}
<div className='player-one' id='player-one'></div>

<h1 onClick={gamestart()}>Press to start</h1>

i have a query. i wrote a javascript function that detects keyboard input and moves the 'player-one' div based on arrow key presses.

function checkk(e){
    console.log(e.keyCode)
    if(e.keyCode == 38){
        if(document.getElementById('player-one').getBoundingClientRect().top < 503){
            e.preventDefault(); 
            var vertical = document.getElementById('player-one').getBoundingClientRect().top;
            document.getElementById("player-one").style.top = vertical - 0.5 + "px";
            console.log(vertical)
        }
        else{
            e.preventDefault(); 
        }
        
    }
    if(e.keyCode == 40){
        e.preventDefault(); 
        var verticalb = document.getElementById('player-one').getBoundingClientRect().top;
        console.log(verticalb)
        console.log("0.5")
        var newv;
        var newv = verticalb+0.5
        console.log(newv)
        document.getElementById("player-one").style.top = newv +"px";
        console.log(newv)
    }
}

However, it seems like the code is not functioning correctly as the top value for 'player-one' div keeps increasing regardless of whether I subtract or add 0.5.

here is my css styling for player-one:

.player-one{
    position: relative;
    top: 50px;
    left: 10px;
    width: 25px;
    height: 65px;
    background-color: aliceblue;
}

I attempted to decrease the top value when the up arrow key was pressed, and increase it when the down arrow key was pressed, but unfortunately, it seems to be increasing in both cases.

Answer №1

Here are a couple of pointers:

In your CSS, you are using the class selector ".player-one" instead of the ID selector "#player-one". Make sure to use "#player-one { css here }" for proper styling.

To save time and avoid repetitive typing, consider saving the element selection in a constant variable. In this case, it would be:

const playerOneEl = document.getElementById("player-one");

Afterwards, you can simply use the constant variable like this:

playerOneEl.style.top = `${newv}px` 

(You can learn more about template literals here)

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

When a user clicks on an image, I would like to dynamically resize it using a combination of PHP

Although I have a good understanding of CSS and HTML, my knowledge of Javascript is limited. I am looking to add an interactive element to my website where an image enlarges gradually when clicked and smoothly moves to the center of the screen in one con ...

Erase embedded frame from a Google Sheets document

Is there a way for me to customize the frame and replace it with my own design? Click here to view the Google Sheet embedded frame ...

How can I add scrolling functionality to the active list item with React?

I created a music player that allows users to search for songs by artist. Check out the CODE SANDBOX here! Take a look at how the SongsList component is structured in my project: const SongsList = (props) => { const { loading, errorMess ...

Using PHP and jQuery to generate push notifications can result in issues with server performance

To simulate push notifications using PHP, I have implemented the following method: An AJAX call is made to a server-side script using jQuery. The script includes a for loop with a sleep function after each iteration to introduce delay. If a certain condi ...

Determining the size of an object in ASP.net as a percentage of the page, while taking into account the size of

I need help adjusting the size of a silverlight app on a page with multiple banners above it. My goal is to make the app's height always 100% of the screen height minus the banner's height to prevent any scroll bars from appearing. Does anyone kn ...

Drag and drop a Jquery image onto the div with its top left corner

Drop targets: <div id="targetContainer" style="width:100px; height:100px;> <div id="tar_0-0" class="target" style="position: relative; float:left; width:50px; height:50px; background-color: #fff;"></div> <div id="tar_1-0" class="t ...

Angular 8 UI not displaying mockAPI data as expected

My mockAPI is successfully fetching the data, but the json response structure is quite complex. It looks something like this: [ { "planList": [ // plan details here ] } ] Everything in the UI is displaying correctly, except ...

Troubleshooting a Problem with JSON Array in JavaScript/jQuery - Understanding Undefined Values

Currently, I am fetching data from a JSON file: [ { "video": "video/preroll" }, { "video": "video/areyoupopular" }, { "video": "video/destinationearth" }] I have attempted to use console.log at different stages and encountered an issue when p ...

Deploying a single node.js app on two separate servers and running them simultaneously

Is it possible to set up my game to run on both the west coast and east coast servers, while still using the same domain? In my code structure, app.js runs on the server with the home route serving as the entry point for the game. This means that users si ...

Creating a dropdown menu in Bootstrap 4 using JSON information

I am trying to create a dynamic drop-down menu using an input field with a drop-down button inside a form. Currently, I am attempting to populate the drop-down menu with static JSON data. However, I am encountering issues with getting it to function proper ...

Displaying or hiding table columns in Vue.js Element-UI el-table based on screen width: a step-by-step guide

Here is my code snippet for generating a table: <el-table :data="tableData" empty-text="No data to display :( " v-if="window.width > 855"> <el-table-column v-for="column in tableColumnsMd" :key=&q ...

I am attempting to dynamically align the images of two articles. The exact heights of the containers are not specified. Can anyone provide guidance on how to achieve this?

My code snippets: <article class="featured"> <img src="http://www.placehold.it/300x100/ff0000"> <p> <!--Text--> </p> </article> <article class="sub-featured"> <img src="http://www.placeh ...

Avoiding the utilization of HTML forms

Is it acceptable to send form information using jQuery instead of creating an HTML form? By skipping the traditional HTML form and using $.ajax in jQuery, are there any security, performance, or semantic issues to be concerned about? Does this approach a ...

Guide on setting a value in $(document).ready using code behind

I am currently working on a .NET application with the use of Twitter Bootstrap. My main challenge right now is retrieving data from a .aspx.cs page to a .aspx page. Here's a look at my code: strObject.cs public class strObject { public string Nam ...

Client.db is undefined error encountered in MongoDB backend API

I'm having trouble retrieving data from a collection in my MongoDB backend. Every time I try, I encounter an error stating that the client is not defined. Has anyone else experienced this issue and knows how to resolve it? Error: Client is not define ...

Scaling of SVG elements with a fixed canvas size across different end-user resolutions

I am currently using Power BI and the HTML Content visual to create a .svg image. The canvas default size is 1280x720, which cannot be changed. I designed the .svg in Canva at 1920x1080 resolution to accommodate both 720P and 2K users. To make the .svg dyn ...

In JavaScript, the price can be calculated and displayed instantly when a number is entered into a form using the input type 'number'

Is there a way for me to automatically calculate the price and display it as soon as I enter a number into my form? Currently, the price is only displayed after I press submit. <script type="text/javascript"> function calculatePrice() { ...

What is the best way to process an API call entirely on the server without revealing it to the client?

Seeking guidance on a technical issue I've encountered. On my website, x.com, a form submission triggers an API call to y.com, yielding a JS hash in return. The problem arises when Adblocker Plus intercepts the content from y.com, causing it to be bl ...

Implementing cross-app module injection in Node.js

I have two node apps/services that are currently running together: 1. the main app 2. the second app The main app is responsible for displaying all the data from different apps in the end. Currently, I have taken some code from the second app and integra ...

Tips on saving a form submit button data to localStorage

As a newcomer, I am on a quest to make this function properly. My goal is to create a form where the submit button saves data to the localStorage. Here's what I have tried thus far. <script> function storeRecipe() { localStorage.setItem($(" ...