Converting a Multidimensional Array from Jquery to HTML

In an attempt to arrange pieces on the board in a specific order, I have shared the following code. The idea is to move the pieces by clicking the buttons below the board, with a total of eight moves. I plan to implement fast-forward and rewind buttons as well. However, I am facing challenges with getting the first piece to move successfully.
Despite seeing the movements in the console log and console itself, I am unsure about how to include them in the HTML that I have written. Additionally, the board's responsiveness appears distorted in the snippet window due to dimension constraints but looks normal in full-page view.

$(document).ready(function() {
   "use strict";
  // various move sequences here...

// Board setup with initial configuration
var board = [...];

// Moves configurations
var move1 = [...];
var move2 = [...];

// Counter to keep track of moves
var counter = 0
var moves =  [move1, move2, ...]

// Piece definitions...
var p1 = $('.p1');
var r = ('.white-rook');
var n = ('.white-knight');
...

// Click event to move pieces forward
$('.forward').on('click', function() {
    counter++;
    if (counter == 1) {
      // Specific moves with piece shifting and appending logic
      console.log("Click click BOOM!");
      move1.join('\n') + '\n\n';
      move1[4][3] = move1[6][3];
      move1[6][3] = ' ';
      console.log(move1.join('\n'));
      move1.join('\n');
      e1.append(p1);
      console.log("Move 1");
    };
  });

});
/* CSS styling... */
<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.css">
    <link rel="stylesheet" type="text/css" href="assets/font/flaticon.css">
    <link rel="stylesheet" href="assets/css/styles.css">
    <meta charset="utf-8">
    <title>CHESS, YO!</title>
  </head>
  <body>
    <div class="wrapper">
    <!-- Board configuration... -->

    <button class="reverse"><</button>
    <button class="forward">></button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.js"></script>
<script src="assets/js/script.js"></script>
  </body>
</html>

Answer №1

When creating a board with specified columns and rows, using an HTML <table> with appropriate rows and cells rather than divs can be a suitable choice and the ideal tool for the task. This approach can also enhance responsiveness, preventing layout issues when the board is viewed on a small viewport. If the objective is simply to visually move the pieces, a more efficient method than altering the HTML structure is to update the background images of the elements. By keeping track of the board array and dynamically assigning background images based on the array values, the process can be simplified and error-free.

HTML:

<table>
    <tr>
        <td>&nbsp;</td>  // Repeat 8 times, changing only the background class (consider assigning IDs like 11 for A1, 12 for A2, 21 for B1)
    </tr> // Repeat 8 times for the 8 rows
</table>

JS:

function move1() {
board[7][4] = "p1";
board[5][4] = "e1";
}

function redrawBoard() {
for(var i=0;i<8;i++) {
    for(var j=0;j<8;j++) {
        switch(board[i][j]) {
        // Handle each piece:
        case "Q":
            document.findElementById(i.toString()+j.toString()).style.background-image="Queen.png";
            break;
        case " ":
            document.findElementById(i.toString()+j.toString()).style.background-image=none;
            break;
    }
}
}

In essence, by updating variables in the board with each move and then utilizing a function to iterate through and redraw the board, the HTML structure remains untouched. This method is straightforward, efficient, and reliable.

PS: The inline-table CSS property specifies that the element should behave as an inline <table> element. It does not alter the behavior of table cells. Additionally, consider adjusting the sizes of the table pieces for better responsiveness, ensuring the board scales appropriately on smaller viewports like smartphones or within iframes.

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

Is there a way to specifically modify the color of the last digits in a number?

Seeking guidance on changing the color of the last digits of a number if it ends in a zero or more. For instance, transform 0.50 to 0.50, 10.00 to 10.00, 10,000.00 to 10,000.00, 100,050.00 to 100,050.00, and the like. Any assistance in achieving this would ...

Verify the authenticity of a date using the locale parameter in the Intl API

Seeking advice for validating inputfield based on locale argument. How to format dates differently depending on the specified locale? For example, if locale is 'en-uk' then date should be in mm/dd/yyyy format, but if locale is 'de-ch' i ...

Creating a dropdown menu populated with MYSQL table values using PHP

Can someone help with showing a table row from phpmyadmin named "Team" in a dropdown menu? I am trying to have all the teams listed in a dropdown menu on my page, but it isn't working as expected. <form action="" method="post"> <select n ...

Utilizing knockoutjs to send a MultipartFile along with additional data in an ajax request

Here is a sample form I am working with: <form id="form"> <ul> <li><label>Picture</label> <input id="upload" name="Picture" class="k-textbox" data-bind="value: picture" type="file"/> </li> < ...

Issues encountered while attempting to convert HTML Image and Canvas Tags to PDF within Angular 2

I am currently facing an issue with my code. My requirement is to download HTML content as a PDF file. I have been successful in downloading text elements like the <p> tag, but I am encountering difficulties when trying to download images and canvas ...

Struggling to place the sans-serif font right at the edge of the H1 tag

Encountering a strange issue that suggests I might be overlooking something simple. Any thoughts on the following: I have a heading tag styled with a sans-serif font (loaded from Google fonts) and when I apply a background-color, the text does not align t ...

Issues with Jquery DataTables Component not functioning as expected

I'm a beginner in jQuery and I downloaded this but there aren't enough tutorials available. If anyone knows how to do this correctly, please help me out. It's been difficult for me to figure it out because when I search online, I can't ...

JavaScript - Utilizing an image file in relation to a URL pathway

Is there a way to reference an image URL using a relative path in a JavaScript file similar to CSS files? To test this, I created two divs and displayed a gif in the background using CSS in one and using JavaScript in the other: -My file directory struct ...

The stylesheet malfunctioned while attempting to load varying layouts in separate controllers

Hey, I encountered a strange issue. After clicking on the three pages displayed in the images below: Step 1 controller welcome Step 2 other controllers Step 3, back to step 1 view controller welcome The final image, when returning to controller welcom ...

Ways to insert a div element into the HTML display utilizing JavaScript

There's a method I'd like to use to dynamically add a div to the view using JavaScript. I attempted hiding the div on page load and then showing it through JavaScript. However, what ends up happening is that the div content appears briefly on l ...

"Implementing a function triggered by a change event within a concealed input

I am working with two AJAX functions. The first function takes the input from the first field, concatenates a string to it, and then updates the value of the second hidden input field. However, the second function is supposed to detect any changes in thi ...

What is the best way to implement autoplay sound on a JavaScript webpage?

I'm currently working on a web system aimed at monitoring values from a database, and I have the requirement to trigger a sound alert when a specific range of values is received. Despite trying various examples found online, none of them have been suc ...

How can I modify cell padding using a media query for a specific screen resolution?

In the desktop view, which is larger than 480px, I need a specific <td> to have a left-padding of 9px. However, once the resolution goes below 480px, this left-padding should increase to 18px. At the moment, my padding definition is specified within ...

An Illustrative Example of Inheritance in Javascript?

I've been searching on various platforms for a straightforward example of inheritance without much luck. The examples I've come across are either too complex, obscure, or just not user-friendly. I have multiple service functions that all share so ...

Page redirects automatically after AJAX call

I'm a beginner when it comes to using AJAX and I am trying to delete a student from a list through an AJAX request. I want the response of the request to be displayed on the same page within a specific div, but instead, the response keeps redirecting ...

The Vanishing Act of Bulma Dropdowns in Vue Router

On regular pages, the dropdown feature functions flawlessly. However, when using Vue-router in a single-page application (SPA), the dropdown menu seems to vanish between the navbar-item and its child navbar-link unless the cursor is moved quickly from one ...

A guide on incorporating the CSS 'content' property with the 'option' tag

Is it possible to include CSS 'content' in the 'option' tag? For example, I want to display "Name: Volvo". <html> <head> <style> option:before { content: "Name: "; } </style> </head> <body> ...

QuickFit, the jQuery plugin, automatically adjusts the size of text that is too large

I have incorporated the QuickFit library into my website to automatically resize text. However, I am running into an issue where the text is exceeding the boundaries of its containing div with a fixed size. This is something I need to rectify. This is ho ...

How to create a vertically scrollable div within another div by utilizing scrollTop in jQuery

I need assistance with scrolling the #container div inside the .bloc_1_medias div. The height of #container is greater than that of .bloc_1_medias. My goal is to implement a function where clicking on the "next" and "previous" text will scroll the #contai ...

Having trouble retrieving the value of the hidden field using ng-model

Hello, I'm currently learning AngularJS and facing some challenges with accessing hidden field values using ng-model. Specifically, I am working on an editing modal where I need to retrieve the ID for each record. Below is my controller code snippet: ...