Change the location of an html td element with JavaScript

I am currently working on a simple JavaScript car racing game where the cars are represented by HTML table elements. I want to implement functionality where pressing the "e" key moves player one's car and the "d" key moves player two's car. This will be achieved by using an event listener to detect key presses and move the cars accordingly by updating the table cells. Any guidance on how to achieve this would be greatly appreciated! Below is the code I have so far:

    document.addEventListener('DOMContentLoaded', function() {
      // Code to be executed
      
      function move(player) {
        /*
        Pseudocode:
        
        If Keypressed = "E"
        Move first car forward
        Else if d, move second car forward
        
        Check if player 1 has reached the end of the race track
        Add up total moves for player 2
        */
      }
      
      function keyPress(e) {
        if (e.key === "e") {
          // Move player one
        } else if (e.key === "d") {
          // Move player two
        } else {
          alert("Invalid keystroke");
        }
      }

    });
    .racer_table td {
      background-color: white;
      height: 50px;
      width: 50px;
      border: 5px;
      border-color: black;
    }

    .racer_table td.active {
      background-color: black;
    }
    <link rel="stylesheet" type = "text/css" href="style.css">
    <script type="text/javascript" src="racer.js"></script>
    <body>
      <table class="racer_table">
        <tr id="player1_strip">
          <td class="active"></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
        </tr>
        <tr id="player2_strip">
          <td class="active"></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
          <td></td>
        </tr>
      </table>
    </body>

Answer №1

To implement this functionality, you can first define a variable with the target object and then utilize jQuery's 'next' method to select the adjacent sibling object. For instance, if you insert the following button <button id="x2"/>, it will serve as a demonstration:

$("#x2").click(function() {
    var current = $("#player2_strip").children(".current");
    current.next().addClass("current");
    current.removeClass("current");
});

Answer №2

An alternative approach without using jQuery is possible. While there may be other solutions that do not require an id, the following method appears to be more organized. By assigning a unique id to each <td> element such as 'tile1e', 'tile2e', etc., you can structure your keypress function like so:

function keyPress = function(e){
    if (e.charCode == "e"){
        var tile = document.querySelector("#player1_strip > .active");  // retrieve player tile
        var nextTile = 'tile' + (tile.id[4] + 1) + 'e';  // identify the id of the next tile
        tile.className = "";
        document.getElementById(nextTile).className = "active";

    } 
    else if (e.charCode == "d"){
        var tile = document.querySelector("#player2_strip > .active");  
        var nextTile = 'tile' + (tile.id[4] + 1) + 'd';  
        tile.className = "";
        document.getElementById(nextTile).className = "active";

    }
    else{
        alert("Invalid key stroke");
    }
}

A sample table structure could resemble the following:

<table class="racer_table">
  <tr id="player1_strip">
    <td id='tile0e' class="active"></td>
    <td id='tile1e'></td>
    <td id='tile2e'></td> 
    <td id='tile3e'></td>
    <td id='tile4e'></td>
    <td id='tile5e'></td>
    <td id='tile6e'></td>
    <td id='tile7e'></td>
    <td id='tile8e'></td>
    <td id='tile9e'></td>
  </tr>
  <tr id="player2_strip">
    <td id='tile0d' class="active"></td>
    <td id='tile1d'></td>
    <td id='tile2d'></td>
    <td id='tile3d'></td>
    <td id='tile4d'></td>
    <td id='tile5d'></td>
    <td id='tile6d'></td>
    <td id='tile7d'></td>
    <td id='tile8d'></td>
    <td id='tile9d'></td>
  </tr>
</table>

The concept should now be clear.

While this method is provided, it is also acceptable to utilize the jQuery solution if preferred for its simplicity and convenience.

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

Modifying website elements with JavaScript

Can someone assist me with getting a script to work on my website that will allow me to switch between four different sets of content using buttons labeled 1, 2, 3, and 4? I have tried using addClass and removeClass but cannot seem to get it right. Here i ...

Changing the class of an element in Svelte: A step-by-step guide

I am working on a svelte application and I want to implement row highlighting when a user clicks on it. Here is an example code snippet that demonstrates this functionality: <div id="A" class="car-even">A</div> <div id=&q ...

Transfer the @font-face declaration from the global CSS file into the MUI Theme

In my project, I have an index.css file that includes the following @font-face declaration: //Index.css ... @font-face { font-family: "My Font"; font-style: normal; font-display: swap; font-weight: 400; src: url(/public/fonts/my-font.eo ...

Merging two arrays with lodash for a seamless union

Here are two arrays I'm working with: arr1 = [ { "key1": "Value1" }, { "key2": "Value2" }, { "key3": "Test3" }, { ...

Angular Inner Class

As a newcomer to Angular, I have a question about creating nested classes in Angular similar to the .NET class structure. public class BaseResponse<T> { public T Data { get; set; } public int StatusCo ...

Utilize the function specified in an external file

In my project, I have a typescript file named "menuTree.ts" which compiles to the following JavaScript code: define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var Menu ...

Discovering the property name of an object in Angular using $watch

Is there a way to monitor an object for changes in any of its properties, and retrieve the name of the property that changed (excluding newValue and oldValue)? Can this be accomplished? ...

Can you explain how the Facebook Like button code functions and how I can create a similar feature on my own platform?

I have a website with 250 different items, each containing its own Like button using the standard Facebook "Like" code: div class="fb-like" data-href="http://www.mywebpage.com/myproductpage" data-send="false" data-layout="button_count" data-width="80" dat ...

JS Issue with Countdown functionality in Internet Explorer and Safari

I am having an issue with a JavaScript countdown not working on Internet Explorer and Safari, despite being tested on Windows 7. It works fine on Chrome and Firefox. I am unable to switch to a jQuery countdown due to certain restrictions on the website, so ...

Respond to the initial message within the "if" statement

client.on('message', message => { if (message.channel.type === 'text' && message.channel.name.toLowerCase() == "channel-2" && message.content === "test") { message.react("✅") } ...

Guide to aligning a URL in an HTML file

Greetings all, I'm new to HTML and struggling with how to center a URL on my webpage. For example: <a href="http://www.google.com"> Click Here to Open Google </a> I attempted using the tag and the STYLE attribute but without success. ...

Utilizing Python to manipulate the 'select' tag in HTML

Currently, I am attempting to retrieve events from an HTML page located at In my efforts to choose different areas using python script, I encountered a challenge with the following snippet of HTML code: <select data-ng-options="key as value.name for ( ...

Using an external JavaScript script may encounter difficulties when loading pages with jQuery

Trying to utilize jQuery for loading html posts into the main html page and enabling external scripts to function on them. Utilizing a script (load.js) to load posts into the index.html page: $(document).ready(function () { $('#header').loa ...

Execute a function within a different function once the ajax call has been completed

There's an issue with the timing of my function that runs inside another function. It seems like sometimes the ajax call to the server isn't completed before the function is called. function obtainPlans(row, user, id, type) { $.get( "/ ...

The submitHandler for AJAX does not function properly when using bootstrapvalidator

I'm encountering an issue with the Bootstrap validation tool found at https://github.com/nghuuphuoc/bootstrapvalidator The submitHandler function seems to be malfunctioning for me. Upon form submission, the entry is not being created and the form rel ...

Step-by-step guide to implementing dynamic field autocomplete using AJAX techniques

Seeking assistance in merging ajax autocomplete with dynamic field input. The autocomplete feature is currently working on the first field, but when adding another field, the autocomplete stops functioning. Any help would be greatly appreciated. Here is t ...

Can files in a directory be listed using JavaScript without the need for HTML tags?

Currently, I am exploring ways to automate an Angular application using Protractor. During this process, I encountered a situation where I needed to retrieve a list of all the files within a specific folder. In Java, I am aware that we can accomplish this ...

What methods can be implemented to ensure uniform usage of a single library version among all developers?

Our team utilizes Angular and Visual Studio Code for development, while GitHub serves as our code repository. While this setup has been effective, we recently encountered an issue where one developer had a different version of a particular library. This di ...

Bringing in a legacy ES5 module for integration within a ReactJS component

Attempting to incorporate an ES5 module into a new ReactJS application has been quite the challenge. I'm struggling with understanding the correct way to import the module so that the main function within it can be accessed and executed. Currently, m ...

Is it possible to utilize jQuery to insert a chosen form into a table?

Here is the code example I am working with: <label for="">Select Ticker: </label> <select class="form-control" style="display: inline" id='selected'> {% for p in tickers %} <option value="{{ p.tick ...