Showcasing various images simultaneously within a table cell with the power of JavaScript

For my game project, I need to create an 8x8 table where multiple coins are displayed simultaneously for 3000 milliseconds at random positions. When the "Start" button is clicked, the coin display should continue for 1 minute. However, I am facing an issue with a random function that is generating images on different positions. The error message "appendChild undefined" keeps popping up and I cannot figure out why. I want the image to be displayed randomly across the table without any specific order. Here is the code snippet I have been working on:

PS: I am new to JS and still learning, so please bear with any mistakes in my code.


var tbl = document.createElement('table');
var tr = tbl.insertRow();
var td = tr.insertCell();
var div = document.createElement('div');
div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image">';
var img = document.getElementById("coin_image");

function tableCreate() {
    // Table creation logic here
}

function onTimer() {
    // Timer logic here
}

function onRestart() {
    // Restart logic here
}

.button_class {
  float: left;
  display: inline-block;
  width: 400px;
}

.btn {
  width: 140px;
  height: 50px;
  margin: 20px;
  font-size: 16px;
  background-color:
}

.coin_img {
  width: 100%;
  height: 70px;
  display: none;
}

.counter_div {
  margin-left: 20px;
}
<body onload="tableCreate()">
  <div class="button_class">
    <button type="button" name="start_button" class="start_button btn" id="st_button" onclick="onTimer()">Start</button>
    <button type="button" name="restart_button" class="restart_button btn" id="rs_button" onclick="onRestart()">Restart</button>
    <div class="counter_div" id="counter">
      <h1>Total Time:-1:00</h1>
    </div>
  </div>
</body>

Answer №1

  • Avoid global declaration of td;
  • To access a random cell, use the getElementsByTagName method, such as
    var td = tbl.getElementsByTagName("td")[randomNumber]
    .

Answer №2

Here are a few issues that need to be addressed:

  1. The code is throwing an error

    Cannot read property 'appendChild' of undefined
    in the onTimer() function on the line:

     td[randomNumber].appendChild(img);
    

    It seems like the variable td is undefined here.

    You have declared 'td' twice.

    The first declaration initializes 'td' globally,

    while the second one is inside the nested for loop

    ...
    for(var i = 0; i < 8; i++){
     var tr = tbl.insertRow();
     for(var j = 0; j < 8; j++){
        var td = tr.insertCell(); //<-- HERE
        var div = document.createElement('div');
        td.appendChild(div);
        div.innerHTML = '<img src="coin.png" alt="coin.png" class="coin_img" id="coin_image">';
        td.style.border = '1px solid black';
        td.style.width = '85px';
        td.style.height = '75px';
      }
    }
    ...
    

    The second declaration is local to the 'functional scope' created by the tableCreate() function. So, when you try to append the image randomly, you end up referencing the global "td," which is just empty and not an array of elements. Updates made to the global td within the loop will only reflect the last referenced value in the loop.

  2. There is also an issue with the random number generation. Generating a number between 0 to 63 won't place the image in one of the 64 td's created in the tableCreate() function because you generated 8 td's for each of the 8 tr's.

    • Generate a random number from 0-7 to select a random row (tr).
    • Generate another random number from 0-7 to select a random column (td) in the row obtained from step 1.

For a demonstration, check out this plnkr demo

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

Issues with clicking in JS eventListener

I'm in need of some assistance with a small header issue in my project. I've included all the necessary header files so that you can run it in a snippet and see what's going on. The problem lies within my JS file. When running the file, you ...

How can I incorporate a personalized SVG path to serve as a cursor on a webpage?

Is there a way to enhance the functionality of binding the 'mousemove' event to a div and moving it around the page while hiding the real cursor? Specifically, can we change the shape of the circle to an SVG path and drag the SVG path around the ...

Placing a logo to the left of a UL list

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> & ...

Working with time durations in JavaScript

Is there a way to calculate the duration between a start time and an end time including both hours and minutes? Currently, I have code that only provides me with the hours. Is there any modification I can make to include minutes as well? If so, what chan ...

Using Node.js to implement pagination with the POKEapi through a loop

Recently, I've been experimenting with the POKEapi to display information on 150 different pokemons. This is my first attempt at creating a node.js app as I'm just starting to learn javascript. The challenge I'm facing now is implementing ...

Aurelia validator fails to refresh user interface

Despite the aurelia-validator plugin working correctly for form submission and validation, with all properties updating properly, the UI does not reflect any changes. There is no red outline around incorrect properties or error messages displayed. I have r ...

Show the WooCommerce checkout shipping fields and eliminate the "Choose a different delivery address?" checkbox

Is there a method to eliminate the checkbox labeled "Ship to a different address?" on the woocommerce checkout page while still displaying the shipping fields? I have attempted the following: add_filter( 'woocommerce_cart_needs_shipping_address', ...

The Pop Up is displaying with half the page showing Opacity or Page Background

I'm currently working on a project that involves creating a pop-up window. CSS Styling <style type="text/css"> #modalPage { display: none; position: absolute; width: 100%; height: 100%; top: 0px; lef ...

Adjust the prop value whenever there is a modification in the Vuex store

Following a successful mutation to the vuex store (state.posts.post.comments) with the use of this code snippet and implementing Vue.set for Vue to acknowledge the addition of an object property: store/modules/post.js const mutations = { [types.SET_P ...

Execute CSS within jQuery code only when the body class is present

I am attempting to use CSS (display: none;) within a script to hide elements from my menu only if a specific language is active. When the body class changes from one language to another, I want the script to check if the body class of a certain language ...

Is the branch of ExtJS 4.1 TreeStore lazy loading extending?

I am working on implementing lazy loading of tree branches in an MVC application using extjs4.1. The branches are located on different URLs and I have faced several challenges along the way. Unfortunately, at this point, the branching functionality is not ...

Using Vue.js: Execute a function with a delay, but start the delay over if there is any user input

Imagine a scenario where I have a form that is connected to an API and displays information based on user input. Whenever the user makes changes, such as adjusting the number of results per page, the component should react dynamically by loading new data. ...

Attempting to center the text directly above the input field

Is there a way to align text on top of an input box without manual adjustment? Any suggestions on how to achieve this? <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemai ...

creating keys dynamically in a Mongoose schema using Node.js JavaScript

I consider myself an intermediate in node.js. Within my mongoose schema, I have a variety of fields listed below: result_1 result_2 result_3 result_4 result_5 The data will come in numeric form (1-5) as the result number, and based on this number, I nee ...

Using div tags may cause rendering issues

I am trying to use multiple div tags with webkit borders, but for some reason only the one called 'Wrapper' is displaying properly. Here is my code: .wrapper { margin: 20px auto 20px auto; width: 800px; background: url('images/background_1. ...

Implementing yadcf and a fixed column filter in a Bootstrap datatable

I am currently utilizing Bootstrap DataTable in conjunction with the Yadcf filter plugin. The filter is functioning correctly for a regular table, however, when I have a fixed column with a Select2 dropdown, it does not render properly. The dropdown is hid ...

Discovering Ways to Utilize User Controls with JavaScript

How do I manipulate my user control using JavaScript? <body> <form id="form1" runat="server"> <div> <uc1:WebUserControl ID="WebUserControl1" runat="server" Enabled="False" /> <input id="Button1" type="b ...

When transformed into clickable links, the list items start piling up on

Here are two groups of code along with a straightforward question that most people can answer easily, but still worth asking. Below is the initial piece of code with working CSS implementation: <div class="subTopHolder"> <ul class="language ...

Exploring the depths of web automation using Python and Selenium, harnessing the power of a while

Currently, I am navigating through various pages on iens website using Selenium and Python. My goal is to click on the "Volgende" button (which means "next" in Dutch) continuously until there are no more pages left by implementing a while loop. Specificall ...

Dispatching information to a designated Google Analytics tracking code

Within our website, we have a unique dimension that is configured on Google Analytics and utilized when sending the page view event: gtag('config', 'UA-TrackingCode', { 'custom_map': { 'dimension1': &apo ...