What is the best way to incorporate all 4 classes from an array into my schedule without missing any?

I currently have a table displayed on my website.

Within the code, there is a while loop that iterates four times and then assigns the weapon class to four random cells, turning them orange as shown in the snippet below.

$(document).ready(function() {

  var body = document.getElementsByTagName("body")[0];
  var table = document.createElement('TABLE');
  var tblB = document.createElement('TBODY');
  table.appendChild(tblB);

  $("td").addClass('empty');




  for (var i = 0; i < 10; i++) {
    var tr = document.createElement('TR');
    tblB.appendChild(tr);
    $(tr).attr('data-x', i)

    for (var j = 0; j < 10; j++) {
      var td = document.createElement('TD');
      tr.appendChild(td);

      $(td).attr('data-y', j);
    }

  }
  body.appendChild(table);



  var weapons = 0;


  while (weapons < 4) {
    var randomRow = Math.floor((Math.random() * 9) + 1);
    var randomCol = Math.floor((Math.random() * 9) + 1);

    var randomCellNew = $($("tr[data-x=" + randomRow + "] > td[data-y=" + randomCol + "]"));
    if (randomCellNew.hasClass('empty') === true && randomCellNew.hasClass('dimmed') === false) {
      randomCellNew.addClass('weapon').removeClass('empty');
      weapons++
    }
  }

})
table td {
  padding: 25px;
  border: 5px solid red;
  background-image: url('image.png');
  background-size: 100%;
}

table {
  margin: auto;
  position: relative;
}

.weapon {
  background: orange;
  opacity: 0.5;
}

.snowballs {
  background-image: url("snowball.png");
  background-size: contain;
  /* <------ */
  background-repeat: no-repeat;
  background-position: center center;
  -webkit-box-shadow: 0 0 5px 2px yellow;
  -moz-box-shadow: 0 0 5px 2px yellow;
  box-shadow: 0 0 5px 2px yellow;
  position: absolute;
}

.gun {
  background-image: url("gun.png");
  background-size: contain;
  /* <------ */
  background-repeat: no-repeat;
  background-position: center center;
  -webkit-box-shadow: 0 0 5px 2px yellow;
  -moz-box-shadow: 0 0 5px 2px yellow;
  box-shadow: 0 0 5px 2px yellow;
  position: absolute;
}

.nunchucks {
  background-image: url("nunchucks.jpg");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
  -webkit-box-shadow: 0 0 5px 2px yellow;
  -moz-box-shadow: 0 0 5px 2px yellow;
  box-shadow: 0 0 5px 2px yellow;
  position: absolute;
}

.ninjastar {
  background-image: url("ninjastar.png");
  background-size: contain;
  background-repeat: no-repeat;
  background-position: center center;
  -webkit-box-shadow: 0 0 5px 2px yellow;
  -moz-box-shadow: 0 0 5px 2px yellow;
  box-shadow: 0 0 5px 2px yellow;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Instead of assigning the same class to all cells, I am looking at giving each of four of them unique classes so that they can hold distinct images. The goal would be for the loop to place one of four images into each of the four random cells until all four classes are utilized.

I attempted to use :nth of type in CSS, but it did not produce the desired outcome. Is there an alternate method available? One idea I had was to iterate through an array of classes, but I am uncertain about how to implement this.

How can I resolve this challenge while still utilizing the if statement and the randomCellNew variable? Furthermore, please note that all adjustments should occur upon page load rather than through any additional functions or click events.

If the provided code above does not work correctly, you can access it on https://jsfiddle.net/johnroiste/y2qktb8z/4/

Answer №1

If you want to add more elements to a table using JavaScript, consider using an array:

var items = ['apple', 'banana', 'orange', 'grape'];

var fruits = 0;

while (fruits < 4) {
  var randomRow = Math.floor((Math.random() * 9) + 1);
  var randomCol = Math.floor((Math.random() * 9) + 1);

  var randomCellNew = $($("tr[data-x=" + randomRow + "] > td[data-y=" + randomCol + "]"));
  if (randomCellNew.hasClass('empty') === true && randomCellNew.hasClass('dimmed') === false) {
    randomCellNew.addClass(items[fruits]).removeClass('empty');
    fruits++
  }
}

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

Steps to fix issues with Cross-Origin Read Blocking (CORB) preventing cross-origin responses and Cross Origin errors

var bodyFormData = new FormData(); bodyFormData.set("data", "C://Users//harshit.tDownloads\\weather.csv"); bodyFormData.set("type", "text-intent"); //axios.post("https://api.einstein.ai/v2/language/datasets/upload", axio ...

What is the proper method for navigating down a webpage after clicking a hyperlink?

I'm currently developing this webpage. When I click on the "state" (e.g. CA), I expect the page to slide down and display the results. Currently, the results are showing up but without any sliding effect. ...

What could be causing my JSON file not to display when the onclick event is triggered?

I am currently learning JavaScript and JSON, as I am enrolled in a class that focuses on these topics. Our latest project requires us to create a JSON file and use a button along with JavaScript to display its contents. I have spent countless hours trying ...

jQuery Image Slider Failing to Meet Performance Expectations

I have created an image slider that allows users to click on buttons to view specific images. However, my code is not functioning as expected and I need help identifying the issue and resolving it. <!DOCTYPE html> <html> <head> <ti ...

The scroll animation shows unpredictable behavior when moving in both directions, and there may be a delay in response when using the

I'm attempting to create a smooth scroll effect to move to an element at the bottom of the page when scrolling down, and another element at the top of the page when scrolling up. Both elements have a height of 100vh. However, once I start scrolling d ...

MD-List Equilibrium Elevation

Seeking a solution for implementing a simple chat using the md-list template. The issue arises when new items are added to the md-list, causing it to expand. Desiring the list to behave similarly to other chat platforms, where the height remains constant ...

Triggering the microphone to enable listening in Javascript for Webkit Speech recognition

<input x-webkit-speech /> Activates speech input in webkit browsers: Is there a method to programmatically click the microphone button using JavaScript? ...

"Exploring the magic of Vue.js and Three.js: A guide to seamlessly changing CSS style elements within an

I'm currently in the process of converting my Three.js project to Vue.js Within my Three.js scene, I have a 3D model with HTML points of interest attached to it. It is crucial that these points remain fixed to the model and consistently face the cam ...

Is there a reason why I need to rename the CSS file in order for it to function properly?

I recently completed editing the css file and saved it, but unfortunately, my css file isn't functioning properly. The display remains unchanged and the css files are not being loaded. However, when I decided to rename the css file, everything started ...

Investigating Javascript compatibility problems with Firefox 4

In FF3.X and IE7 to 9, the code below is functioning correctly, but in FF4, there seems to be an issue. The following code is used in two different locations within my file: var args = "method=getoptions"; args += "&dr ...

Encountering a console error during the migration of a Vue App with VueRouter

I am currently in the process of integrating a standalone Vue application into a larger Java Spring web project. The Vue app relies on Vue router as a dependency. However, when attempting to load the main page, I encountered an error in the browser console ...

Is following the best pattern for Ajax pagination in CodeIgniter?

I am looking to upgrade the traditional pagination system on a website built with CodeIgniter to a dynamic pagination with AJAX. However, as I am new to AJAX, I am unsure about the correct approach to take. Current Setup The structure of my page is as f ...

My jQuery form is not functioning properly upon initialization

Let's take a look at this sample 'template' code: $(document).on("<EVENT>", "form", function() { $(this).find(".input input").each(function() { var required = $(this).attr("required"); var checkField = $(this).clos ...

Utilizing MVC and JQuery: Optimal Strategy for Gathering Form Information

I have implemented a JQuery functionality utilizing Ajax to send data back to my controller for processing. This is the approach I'm using: //Defining my input controls <%=Html.TextBox("PName", Model.PName, new { id = "pName" })%> ... .... .. ...

Guide to adding an additional border within a div element

In my HTML document, I've created a div element with a border: .box {border: 1px solid black; width: 100%; height: 200px} <div class="box"></div> Now, I'm looking to enhance this div by adding a second vertical line that will divid ...

Enhance Your Tables with jQuery DataTables and JEditable

I am currently working with a DataTable that incorporates jEditable functionality, allowing users to modify values within the 3rd column. However, I have noticed that the AJAX post is not sending the 'ID' which corresponds to the value in column ...

Creating dynamic qtip2 tooltips is an effective way to enhance user interaction on

I am facing an issue where all tooltips work perfectly fine when the page loads, but stop working after data refreshes through ajax. How can I resolve this problem? $(document).ready(function() { // MAKE SURE YOUR SELECTOR MATCHES SOMETHING IN YOUR HT ...

Adding new rows to an existing table header

Utilizing JQuery to dynamically append table rows, but encountering an issue with aligning the rows with the header row. The goal is to have the header row defined in the static HTML and use JQuery to add additional rows below it. However, currently all r ...

When reloading jQuery datatable with AJAX, the form submission is triggered once more

Utilizing jquery datatables to retrieve data from the server, I am also able to edit this table to input new data. However, upon adding auto-refresh functionality after an addition, the create request is being submitted repeatedly. var dataTableInitilizat ...

What is the best way to determine font size based on the width of the

In order to ensure that certain elements on my page do not exceed specific widths, it is crucial for me to use a monospaced font. This will limit the horizontal "stride" between characters to stay within a specified threshold. However, simply setting the ...