Using Javascript to Manuever an Element via Arrow Inputs

Currently, I am in the process of developing a Tetris game with a rotating Tetris piece controlled by pressing the space bar.

My next objective is to enable the movement of objects to the left and right using the arrow keys. After exploring various similar queries on Stack Overflow, I discovered that adjusting margins could make this achievable.


var angle = 0;
var obj = document.getElementById('image')

document.onkeydown = checkKey;

function checkKey(e) {

    e = e || window.event;

    if (e.keyCode == '32') {
        rotate();
    }
    else if (e.keyCode == '37') {
        moveLeft();
    }
    else if (e.keyCode == '39') {
        moveRight();
    }

}
function rotate() {
    angle = angle + 90;
    console.log(angle)
    obj.className = "image" + angle;
    console.log(obj.className)
    if (angle == 360) {
        angle = 0;
    }
}

function moveLeft() {
    obj.style.left = parseInt(obj.style.left) - 5 + 'px';
}

function moveRight() {
    obj.style.left = parseInt(obj.style.left) + 5 + 'px';
}

Despite implementing these changes, I am encountering some challenges.

To further illustrate my issue, I have recreated my code on a JSFiddle platform, replacing the Tetris piece with a banana image.

Answer №1

Your issue lies in the styling, not the Javascript code. To resolve it, you should use absolute positioning for your image (in this case, a banana) and specify an initial "left" value. While the position: absolute; can be defined in either the HTML or CSS, the left: 0; should be included in the HTML style attribute. You can view the updated changes in this updated jsfiddle.

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

How to dynamically inject HTML content from a child component into a different component using Angular 5

Is it possible to customize the content of a reusable header section based on the current route data in Angular? The header currently displays a title and description pulled from the route data property. My concern is how to dynamically inject different H ...

What is the best way to transfer Django variables to HTML?

Looking to send data from the rs232 port and showcase it in a graph using javascript? Check out this resource: Seeking guidance on importing the views.py variable into my html file. views.py import io from django.http import HttpResponse from django.shor ...

Determine the upcoming Saturday's date by utilizing a stored procedure in Snowflake

Looking for assistance in retrieving the upcoming Saturday date based on a date field in a table using a Snowflake JavaScript stored procedure. Any suggestions would be greatly appreciated. Running the following query in the Snowflake console provides the ...

node index of data that has been posted

My HTML file is quite straightforward: <form method="post" action="http://localhost:3000/post"> <input name="name" type="text"/><br /> <input name="last_name" type="text"/><br /> <button id="submit" type="submit"& ...

What steps are needed to link my Javascript application with Amazon Keyspaces?

I am a beginner looking for assistance with extracting data from Amazon keyspaces tables on a small demo website with 4 categories and 4 subcategories. I have created the tables but can't find a tutorial, please help. The goal is to display database ...

Is there a way to search for a specific item within a nested array?

I have 2 arrays within an array, each containing objects. How can I locate the object with the name "Sneijder"? const players = [ [ { id: 1, name: "Hagi", }, { id: 2, name: "Carlos", }, ], [ { id: 3 ...

What is the reason that an individual would stop another from executing by using $(document).ready(function() { ?

While I understand that it's supposed to be possible to run multiple $(document).ready(function() { on my page, for some reason I'm having trouble doing so. I appreciate those who have pointed out that it should work, but I'm really looking ...

Issue encountered with invoking carousel.to() method in Bootstrap 5

// Create a new carousel instance let car = new bootstrap.Carousel(document.querySelector('#carouselMenu'), { interval: 0, wrap: false }); // <SNIP> // Go to page at index 1 car.to("1"); Error: https://i.sstat ...

Creating a template based on an object type in JavaScript with Angular: A step-by-step guide

I have a collection of objects, each with a property indicating its type. Here's an example: [ { "type" : "date", ... },{ "type" : "phone", ... },{ "type" : "boolean", ... } ] I'm ...

Avoid using fs.read without returning a value to console.log

Seeking assistance with parsing a text file named information.txt and displaying the values using console.log. Here is the code snippet: fs.readFileSync("information.txt", "utf-8", function (err, data) { ...

Sparse planeBufferGeometry in THREE.js is a specialized type of geometry that

I am currently working with a file that contains sparse elevation data derived from GPS information. I have been utilizing this data to fill a PlaneBuffer array with elevations. var vertices = new Float32Array( (grid.NCOL*grid.NROW) * 4 ); for (var i = 0, ...

Greetings! I am looking for information on how to activate CORS in a Ruby on Rails API application deployed on OpenShift for use with an Angular

My current setup involves a script utilizing Angular to display records fetched from a Rails API REST, which is hosted in OpenShift. In my public/.htaccess file, I have included the following directives: Header add Access-Control-Allow-Origin "*" Header a ...

When using jQuery and AJAX, the functions each, if, post, and .html work properly but occasionally erase data inexplicably

I have a PHP page containing FedEx and UPS tracking numbers stored in a MySQL database, which are displayed within DIVs with the class "trackingnumber". Using JavaScript, I loop through these divs to retrieve the ID and then send it to a PHP page that fetc ...

What are some creative methods to apply CSS styling to material-table in React?

I've spent several days searching for a solution without any luck. My project involves using material-table in React, and I am struggling to apply CSS styles to the headers (columns) and content (such as changing font size, adjusting width, and creati ...

Challenges with unique scrollbar designs and dynamic tab loading using AJAX

Hello to all amazing members of stackoverflow, I'm facing some major challenges getting my custom scrollbar to function properly with ajax-based tabs. Any assistance you can provide would be immensely helpful. I have most of it set up and operational ...

React Alert Remove Alert: Each item in a list must be assigned a distinct "identifier" prop

How can I resolve the React warning about needing a unique "key" prop for each child in a list? I'm trying to eliminate the warning that says: "Each child in a list should have a unique key prop." The code snippet causing this warning is shown below ...

Form a bond with the latest SignalR library to initiate communication

After attempting to connect to an asp.net core signalR server using the code below, I encountered some issues. Can you spot where I might have gone wrong? Here is the error message that I received: Error: The "promise" option must be a Promise v ...

using async.waterfall with async.apply

Here is a code snippet that I am working with: async.waterfall([ // Read directory async.apply(fs.readdir, '../testdata'), // Load data from each file function(files, callback) { async.each(files, loadDataFromFile, callback); } ], ...

Innovative guidelines originating from a resource attribute

I am facing a challenge with a repeater for a resource that has an attribute containing angular directives mixed with text. My goal is to display form inputs dynamically based on the object's property. <ul> <li ng-repeat="action in actions ...

Endless jasmine timeout

This question is a continuation of a discussion on the Remove timeout for single jasmine spec GitHub issue. Query: Can a single test be configured to never time out? The Issue: While it's possible to set a global timeout value using DEFAULT_TIMEOU ...