What is the best way to steer a vehicle in the desired direction by utilizing the arrow keys on the keyboard?

Image1 Image2

While using visual studio code, I noticed that I can move a car forwards and backwards with the arrow keys on the keyboard. However, it doesn't seem to turn when I try to move in opposite directions. Is there a way to achieve this through animation? Additionally, I encountered an issue where the movement didn't work within a code snippet, although it functions properly in my visual studio code environment.

var bodyEl = document.querySelector("body");
var boxEl = document.querySelector("div");


var left = 0;
var top = 180;

var speed = 10;

bodyEl.addEventListener ("keydown", moveBox);

function moveBox(e) {
    if (e.keyCode === 37) {
        left -= speed;
    }

    else if (e.keyCode === 39) {
        left += speed;
    }

    else if (e.keyCode === 38) {
        top -= speed;
    }

    else if (e.keyCode === 40) {
        top += speed;
    }


    boxEl.style.top = top + "px";
    boxEl.style.left = left + "px";

}
body {
    background-image: url("https://i.stack.imgur.com/x1iaz.jpg");
    cursor: none;
    overflow: hidden;
}

div {
    position: absolute;
    top: 180px;
}
<div><img src="https://i.stack.imgur.com/9dPYr.png" height="300px" width="300px" ></div>

Answer №1

Try animating a box by adding a custom class when the right arrow key is pressed, and removing it when the left arrow key is pressed. You can do the same for the up and down arrow keys.

Add this CSS -

div.reverse img {
 -webkit-transform: scaleX(-1);
  transform: scaleX(-1);
 }

Update the JavaScript function -

function moveBox(e) {
    if (e.keyCode === 37) {
        boxEl.classList.remove("reverse");
        left -= speed;
    }

    else if (e.keyCode === 39) {
        boxEl.classList.add("reverse");
        left += speed;
    }

    else if (e.keyCode === 38) {
        top -= speed;
    }

    else if (e.keyCode === 40) {
        top += speed;
    }


    boxEl.style.top = top + "px";
    boxEl.style.left = left + "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

Exporting Data and Utilizing a Steady Data Table

I have incorporated the Fixed Data Grid into my latest project. https://facebook.github.io/fixed-data-table/example-sort.html My goal is to generate csv and pdf reports from the data displayed on the grid. Could you please advise me on how to export gri ...

Prevent the ability to add options dynamically to a drop-down select list

I have implemented a dynamic data retrieval feature from my database using jQuery's .getJSON function and appended the data to an HTML select drop-down list. The JavaScript code for this functionality is as follows: $.getJSON('url', f ...

Overriding a CSS property with !important proves ineffective

I need to make adjustments to an old internal page that currently has the following CSS styling: table { font-family: "Arial"; font-size: 13px; text-align: left; border-collapse: collapse; border: 1px solid black; vertical-align: m ...

When text is wrapped within the <li> tag

In this div, the structure is as follows: <div class="box1" id="infobox"> <h2> Point characteristics: </h2> <div style="padding-left:30px" align="left"> <ul> <li class="infobox_list"><b>X value: </b>< ...

I am having trouble getting the (:active) pseudo-class to function properly with the menu on my WordPress theme

Purchased a theme called HelpGuru and encountering issues with the CSS of the menu. Reached out to support but they were unable to assist, directing me to a company that specializes in customizing WordPress themes instead. The link to the demo can be found ...

"Exploring the possibilities of integrating the Twitter API with

Currently, I am attempting to access my most recent tweet from Twitter using https://github.com/jdub/node-twitter I am interested in setting a variable, modifying that variable within a function, and then utilizing it again outside of said function. Is th ...

In the world of HTML5, you can find the <main> nestled within the <

Plot: As I was creating a coupons website, I came across the issue of incorporating non-unique content into the <main><article> ..here..</article></main>. Problem: Despite w3schools' statement : The content inside the eleme ...

The Jquery Object #<Object> does not have the 'getElement' method available

I've been attempting to set up this table, following the instructions here: Despite verifying that my browser is correctly pulling the CSS and .js files, I keep encountering an error related to my sortabletable.js file. (screenshot of the error) htt ...

Is it possible to retrieve AJAX data through a callback function?

I have encountered an issue where the ajax success function does not return data as expected. I attempted to use a callback function instead, but I still end up with undefined results. I resorted to using the variable responseText, however, I am looking fo ...

How can I restrict the selection of only one checkbox within an iframe window?

Here is my JavaScript snippet: var iframe = document.getElementById('pltc'); iframe.contentWindow.document.open('text/htmlreplace'); iframe.contentWindow.document.write('<input type="checkbox" name="tc0">Yes<input type="c ...

Encountering module resolution issue following npm-link for the shared component repository

Attempting npm-link for the first time to establish a shared component repository, and encountering an issue. The project seems to be linked correctly based on this message: /Users/tom.allen/Development/main/project/node_modules/@linked/project -> /usr ...

Creating a unique navigation route in React

My application has a consistent layout for all routes except one, which will be completely different from the rest. The entire application will include a menu, body, footer, etc. However, the one-off route should be standalone without these elements. How ...

Is it possible to assign multiple ID's to a variable in jQuery?

I am currently using a script for a slider known as Slicebox, and in order to have different image sizes for mobile and desktop views, I need to duplicate the feature on my website. Although it's not ideal, I really like this slider and want to explo ...

Incorporating fontawesome icons ABOVE custom menu items in WordPress

In the process of customizing a menu in WordPress, I am looking to add fontawesome icons above each list item. In the past, I achieved this using the following code: <ul> <li> <a href="#"> <i class="fa fa-home"></i&g ...

ExpressJS refuses to wait for my promise to be fulfilled

I'm in the process of creating a search-page on my server. Whenever the endpoint is accessed and the user waits for the search function to deliver the results and display them on the page, Express somehow redirects to the 404 handler instead. An error ...

Interactive Text Transformation on Mouse Over

My goal is to create a sleek and clean Index page featuring a simple white background with text centered in the middle. The initial text will be: USEStudio Upon hovering the mouse, the text will transform into: ...

Firebase User Becomes Undefined Upon Refreshing the Web Page

My situation is quite straightforward. I have developed a Firebase web application and I am logging in with my Google account. The problem arises when I have to keep logging back in every time the page is refreshed, as depicted in these steps: Initialize ...

The edit functionality in jqGrid does not function properly if custom search parameters are designated

Using the Guriddo jqGrid JS version 5.2.0 implemented here: @license Guriddo jqGrid JS - v5.2.0 - 2016-11-27 Copyright(c) 2008, Tony Tomov, [email protected] The code block below showcases an entire self-contained implementation of jqGrid. It inclu ...

What is the solution for - Uncaught TypeError: Cannot access the property 'scrollHeight' of an undefined element?

Could someone kindly assist me in resolving an issue? I recently encountered a problem with a script I have been using on the Chrome console. This script has been working perfectly fine for the past few days. However, today when I ran it, I started receiv ...

Auto-collapse sidebar upon clicking anywhere on the page

I have a dynamic sidebar that appears when the user clicks on a hamburger button. Here is the layout: $('#nav-toggle').click(function() { if($('#nav-toggle').hasClass('active')){ $('.menu').animate({ r ...