What could be causing my div element to remain stationary despite the movement functions I have implemented?

I am attempting to move my div element by using key presses to adjust the CSS attributes of the HTML elements. However, despite implementing the necessary code, the mover refuses to budge and nothing appears when I inspect the elements or their attributes.

var mover; 

function moveDivBlock(e){
    if ((e.keyCode == 69) ||(e.keyCode == 68)||(e.keyCode == 67)){//go right
        moveBlock(mover,10,0);}
    if ((e.keyCode == 81) ||(e.keyCode == 65)||(e.keyCode == 90)){//go left
        moveBlock(mover,-10,0);}
    if ((e.keyCode == 81) ||(e.keyCode == 87)||(e.keyCode == 69)){//go up
        moveBlock(mover,0,10);}
    if ((e.keyCode == 90) ||(e.keyCode == 88)||(e.keyCode == 67)){//go down
        moveBlock(mover,0,-10);}
}

function handleKeyDown(e) {
    moveDivBlock(e);
}


function moveBlock(elem, rightShift, upShift){
    var curLeft = parseInt(elem.style.left); 
    var curTop = parseInt(elem.style.top); 
    elem.style.left = (curLeft + rightShift) + "px"; 
    elem.style.top = (curTop - upShift) + "px"; 
}

window.onload=function(){
    mover=document.getElementById("mover");
}
#mover{
        position:absolute;
        top:290px;
        left:130px;
    
        background-color:green;
        width:50px; 
        height:50px; 
        border:2px solid black;
}
<body onkeydown="handleKeyDown(event);">
        <div id="mover"></div>
</body>

Answer №1

One of the reasons why the previous solution wasn't working is because elem.style.top retrieves inline styles only, not those from a CSS file. To access styles from a CSS file, you should use getComputedStyle(elem). Give this code block a try:


function moveBlock(elem, rightShift, upShift){
    var curLeft = parseInt(getComputedStyle(elem).left); 
    var curTop = parseInt(getComputedStyle(elem).top); 
    elem.style.left = (curLeft + rightShift) + "px"; 
    elem.style.top = (curTop - upShift) + "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

Tips for personalizing the webpack compilation process for transforming .vue files into .js files?

As a beginner in the realm of webpack plugins, I've grasped the idea behind the html-webpack-plugin, which empowers users to personalize the generation process of html files by webpack. In a similar vein, I am on the quest for a plugin tailored for . ...

Guide on how to turn off cache in AngularJS + NodeJS CRUD application

I'm encountering an issue with cache in Internet Explorer, but everything seems to be working fine in Chrome. Whenever I try to add an item in my application, the data doesn't refresh automatically and I have to press Ctrl+R to manually refresh. ...

Tips for adjusting the angle in SVG shapes

I have designed an svg shape, but I'm struggling to get the slope to start from the middle. Can someone please provide assistance? <svg xmlns="http://www.w3.org/2000/svg" fill="none"> <g filter="url(#filter0_b_1_2556)"&g ...

Automatically update and reload Express.js routes without the need to manually restart the server

I experimented with using express-livereload, but I found that it only reloaded view files. Do you think I should explore other tools, or is there a way to configure express-livereload to monitor my index.js file which hosts the server? I've come ac ...

javascript string assignment

Is it possible to conditionally assign a string based on the result of a certain condition, but for some reason, it's not working? var message = ""; if (true) { message += "true"; } else { message += "false" } console.log(message); ...

JavaScript event listener for SVG path element click is not functioning correctly as anticipated

How to determine if an element or its children have been clicked? I am trying to identify when a parent element or any of its child SVG icons with the attribute name set to "setGameState" have been clicked. The issue I am facing is that sometimes the even ...

Access rejected due to X-Frame-Options: "http://test.test.net/Feedback/Create?appId=TestApp" prohibits cross-origin framing in MVC5

Currently, I am developing a website that is hosted on my company's internal network and can only be accessed from within the network. As a result, cross-domain requests are not a concern for me. As part of this website, I have included a "Provide Fe ...

Convert HTML form input into a JSON file for safekeeping

<div class="email"> <section class="subscribe"> <div class="subscribe-pitch"> </div> <form action="#" method="post" class="subscribe-form" id="emails_form"> <input type="email" class="subscribe-input" placeholder="Enter ema ...

React is informing that the `toggleNode` prop is not recognized on this particular DOM element

I have encountered the following warnings in my app, which I believe are causing it to not load all its features properly. Warning: React is indicating that the toggleNode prop is not recognized on a DOM element. If you intend for it to be a custom attrib ...

Using THREE.js to shoot a ball with a curve on the X or Z axis

As a beginner in THREE.js and lacking knowledge in physics, my goal is to create a top-view football manager game with realistic ball movement. I have successfully made the ball move and rotate in the right direction, adjusting its path when it reaches bou ...

Creating a curved exponential data set with specific endpoints and a set number of data points

Struggling to create a function that involves math skills, I could really use some assistance. The task is to design a function that takes data points x and generates an array of size x with exponentially increasing values from 0 to 100. It would be ideal ...

JavaScript tool package with non-JavaScript alternative

Currently in search of a reliable Javascript widget toolkit that boasts a modern UI design like Dojo, incorporates AJAX for navigation, and effects. Essential requirement is flexibility and seamless fallback to an HTML-only version for console users. Whi ...

In my Node.js application using Express and Passport, I encountered an issue where res.locals.users is functioning properly but the data it

I'm currently working on an application using NodeJS, Express, and Passport. However, I've encountered an issue when trying to display user data in the views. While I am able to retrieve the ObjectID of the user from res.locals.user, accessing s ...

What is the best way to create a mock URL in axios for unit testing purposes?

Scenario In this application, the URL is only accessible in production and cannot be accessed locally. During unit testing, it becomes necessary to mock the response from that URL. Solution Refer to this helpful tutorial for guidance. Current Implement ...

Obtaining the NativeElement of a component in Angular 7 Jasmine unit tests

Within the HTML of my main component, there is a my-grid component present. Main.component.html: <my-grid id="myDataGrid" [config]="gridOptions" </my-grid> In main.component.specs.ts, how can I access the NativeElement of my-grid? Cu ...

After removing an item from the component in reactJS, the immediate rendering of the dynamic component does not seem to be functioning correctly

I am currently creating a dynamic automobile inventory website from scratch using React.js, Express.js, and MongoDB. The data has been successfully loaded from the database and displayed in a tabular format on the client side. My next task is to enable use ...

Is it possible to store a JWT token in local storage when working with Next.js?

We are considering using Next.js for our application, with a focus on client-side rendering for data fetching. The API we will be interacting with is external and requires authentication to access specific user dashboard content. While the homepage will ...

including a callback in a loop

I am attempting to have jQuery delete an element after it has gone through a series of other functions, however the following code executes the remove() command before the for loop runs any iterations. function waves(){ for(i=0;i<=10;i++){ ...

Tips for submitting multiple radio button values in a tabular format

HTML Code: <div class="tab"><h4>Zip Code</h4> <p><input type="text" class="text1" placeholder="Enter zip code..." oninput="this.className = ''" name="zipcode"></p> </div> <div class="tab">& ...

Is it possible for Angular.js to interact with JSTL expression language?

Is it possible for angular.js to interact with JSTL expression language? I am trying to generate ng-options using an array. Here is an example of what I am attempting to accomplish: <select ng-model="detail" ng-init="Categories = '${Categories}& ...