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

Enhance data validation in PHP

I love using Nicedit as a text editor because it allows me to easily add bold and italic formatting to my form fields. However, when I try to store this text in my database, Nicedit adds HTML tags for bold, italic, and other formatting styles. Is there a ...

Preloading images before loading a div using JavaScript

Can you walk me through implementing object first and then mergeObject in JavaScript? I have an interesting scenario where I need to display the original list followed by a merged list after a short delay. How can I achieve this using JavaScript? Specific ...

Determining the appropriate version of the types package for your needs

It has come to my attention that certain npm packages do not come with types included. Because of this, the community often creates @types/packagename to provide those types. Given that both are packages, how does one determine which version of the types ...

Make TypeScript parameter optional if it is not supplied

I am working with an interface that defines scenes and their parameters: export interface IScene<R extends string> { path: R; params?: SceneParams; } The SceneParams interface looks like this: export interface SceneParams { [key: string]: s ...

What's the Best Way to Add a Border to My Two-Column Form?

I'm currently working on a reservation form for my website with a 2-column layout. In one column, I have tables, and I've been trying to add a divider between the columns but haven't found a solution yet. Despite researching ways to add a d ...

Material UI defaults remain unchanged despite any emotional influence

I'm currently experimenting with custom styling on a MaterialUI Typography component using the code snippet below: const StyledTitleTypography = styled(Typography)` color: 'black'; font-weight: 'bold'; `; <StyledTitleTypogr ...

What is the best way for me to insert a paragraph between two lists?

Is it possible to insert a paragraph in between lists even though it's not allowed? Here is an example of the code: <ol> <li>One</li> <p>Paragraph 1</p> <li>Two</li> <p>Paragraph 2</p ...

What is causing my AJAX Contact Form to navigate away from the original page?

I configured a contact form on my website more than 5 years ago, and I vividly remember that it used to show error/success messages directly on the page within the #form-messages div. However, recently, instead of staying on the contact form page and displ ...

Lightbox.options does not exist as a function within the lightbox plugin

I recently incorporated a lightbox plugin into my website, which can be found at the following link: For displaying items on the page, I am using markup similar to this example: <a href="images/image-2.jpg" data-lightbox="my-image">Image #2</a&g ...

How can I implement an AJAX request with MongoDB in Node/Express?

Let's begin with a simple webpage: an HTML Form, a button, and a div-box. When the button is clicked, the Form data will be sent via AJAX. The data will then be stored in MongoDB and retrieved into the div-box seamlessly without any page refresh. A ...

Substitute for SendKeys() in Angular JS web pages using Selenium

Currently, I am utilizing selenium automation to streamline the processes of a third-party website. To input data into form fields, I have been employing the SendKeys() method. While this method is functional, it's time-consuming as there are numerous ...

The Java Selenium script encountered an illegal type error when trying to execute JavaScript through JavaScriptExecutor: driverFactory.CustomWebElement

I have a CustomWebDriver class that extends the functionality of JavascriptExecutor. Here is my implementation: @Override public Object executeScript(String script, Object... args) { return ((JavascriptExecutor) driver).executeScript(script, args); } ...

Error: The function res.json is not recognized. Despite searching through related inquiries, I cannot find a solution to my specific issue

Struggling to find a solution and avoiding repetitive questions, I am facing an issue with my bug tracker. After submitting the form and sending it to the server side, the bug is created in the database. However, when I save the bug using await bug.save() ...

Is there a way to tally the checked mat-radio-buttons in Angular?

I am seeking a way to determine the number of radio buttons checked in a form so I can save that number and transfer it to a progress bar. <mat-radio-group name="clientID" [(ngModel)]="model.clientID"> <mat-radio-button *ngFor="let n of CONST ...

When trying to run the "npm start" command, I encountered a syntax error that specifically mentioned the use of

Every time I attempt to run the npm start command, I encounter the following error: I have followed the steps provided in this link: https://github.com/kriasoft/react-starter-kit/blob/master/docs/getting-started.md Could you please advise on how to resolve ...

Tips for excluding certain parameters in the jslint unparam block

While developing my angular app, I encountered an issue with jslint flagging an unused parameter. Typically in angular, the "$scope" is required as the first parameter in your controller definition. In my case, I prefer using the "this" keyword instead of ...

Deciphering key-value pairs that are separated by commas

I am looking to convert the following format: realm="https://api.digitalocean.com/v2/registry/auth",service="registry.digitalocean.com",scope="registry:catalog:*" Into this JSON object: { realm: "https://api.digitaloce ...

Using AJAX to store values from PHP SESSION into form inputs with POST data

Wondering how to store ajax-sent data from form inputs as session variables? I have already included session_start() in header.php. Saving the code in the database is working fine. Here's what I attempted: HTML form <form action='' meth ...

The div "tags" cannot be positioned beneath the photo as it is automatically located alongside the image inside the div

Is there a way to place the "Tags" div beneath an image, creating a bar of tags below it? I've been struggling to position it properly without disrupting the flow of the page. Using absolute positioning is not an option as it would break the layout. A ...

"In a single line, add an item to an array based on a specified condition

I am trying to achieve something similar in JavaScript with a one-liner. Can this be done without using an if statement? // These versions add false to the array if condition = false let arr = await getArray(params).push(condition && itemToAdd); arr = awai ...