3

First, my coding experience consists of modifying simple scripts to work on my pages. Second, I have searched and found several similar questions, but can't quite work my way through them.

I need some assistance with populating a 3x3 table with random images from an array of approximately 40 images. I currently have a working template that makes use of the backgroundImage property. I would like to change it to use regular images instead of background images so I can eventually add modal images.
I assume that this line of code is what needs to changed

cell1.style.backgroundImage = "url("+images[imagePos]+")";

I've tried several options I've found here and elsewhere. These two links seem the most relevent, but I can't quite seem to pull them together.

Randomly inserting images into table using Javascript

show random image from array in javascript

Any assistance or if there is a better solution that I can be directed to will be greatly appreciated.

<html>
<head>
<title>Random BG Table</title>
<style>
.cell {
    background-position: center;
} 
</style>
<script>

var images = new Array();
    images.push("images/Image_01.jpg");
    images.push("images/Image_02.jpg");
    images.push("images/Image_03.jpg");
    images.push("images/Image_04.jpg");
    images.push("images/Image_05.jpg");
    images.push("images/Image_06.jpg");
    images.push("images/Image_08.jpg");
    images.push("images/Image_09.jpg");


function randomCellBG()
{
    var cell1 = document.getElementById("cell1");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell1.style.backgroundImage = "url("+images[imagePos]+")";

    var cell2 = document.getElementById("cell2");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell2.style.backgroundImage = "url("+images[imagePos]+")";

    var cell3 = document.getElementById("cell3");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell3.style.backgroundImage = "url("+images[imagePos]+")";

    var cell4 = document.getElementById("cell4");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell4.style.backgroundImage = "url("+images[imagePos]+")";

    cell5.style.backgroundColor = "gray"


}
</script>

</head>

<body onLoad="randomCellBG()"><br><br><br>
<table width="600" height="600" border="1" id="mainTable">
  <tr>
    <td width="200" class="cell" id="cell1">&nbsp;</td>
    <td width="200" class="cell" id="cell2">&nbsp;</td>
    <td width="200" class="cell" id="cell3">&nbsp;</td>
  </tr>
  <tr>
    <td width="200" class="cell" id="cell4">&nbsp;</td>
    <td width="200"  id="cell5">title</td>

  </tr>

</table>
</body>
</html>  
dano
  • 37
  • 7

3 Answers3

1

Use the innerHTML property

function randomCellBG()
{
    var cell1 = document.getElementById("cell1");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell1.innerHTML = "<img src='"+images[imagePos]+"' />";

    var cell2 = document.getElementById("cell2");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell1.innerHTML = "<img src='"+images[imagePos]+"' />";

    var cell3 = document.getElementById("cell3");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell1.innerHTML = "<img src='"+images[imagePos]+"' />";

    var cell4 = document.getElementById("cell4");
    var imagePos = Math.round(Math.random()*(images.length-1));
    cell1.innerHTML = "<img src='"+images[imagePos]+"' />";

    cell5.style.backgroundColor = "gray";   
}
Chandan Rauniyar
  • 814
  • 1
  • 14
  • 24
0

Rather than setting the image as the background for the cell, you can create an element via JS and use 'appendChild' function to insert the element in the cell.

0

When you have multiple objects, follow these guidelines:

  • Place multiple objects in separate groups.
    • ex. urls of images = 9 strings / table cells = 5 <td>
  • If any of the groups could be reduced do so.
    • ex. All 9 strings have a path of "images/Image_"
    • ex. The last cell doesn't have a class of .cell and it doesn't get an image.
  • Gather each group into an HTMLCollection or an array and store what's excluded in a variable if it's needed.
    • ex. var base = "images/Image_" var imgs = ['01.jpg','02.jpg',...'09.jpg']
    • ex. var cellArray = Array.from(document.querySelectorAll('.cell'))
  • Run one of the arrays through a for loop or an Array method and on each iteration, run a function that will manipulate both arrays into the desired result.
    • ex. See demo

In the following demo is the refactored function randomCellBG() it will take a given array of image file names (imgs[]) and the path that they are located (base). This function will accept any amount of file names as long as they are in the same location. If you'd like to make it more versatile, you could make the target table a parameter and change the array of cells as <td> instead of .cell classes.

Details are commented in demo

⍟ notes that specifically pertain to OP's code

Demo

/* An array of numbers, each reresenting the 
|| unique part of each image's url
⍟ var imgs = ['01.jpg', ... '09/jpg']
⍟ The array in demo is an array of numbers (no quotes)
⍟ but the one in OP is an array of strings (each are quoted)
*/
var imgs = [1, 2, 3, 4, 5, 6, 7, 8, 9];

/* The part of what each image url has in common
⍟ var base = 'images/Image_'
*/
var base = 'https://placehold.it/100x100/000/fff?text=';


function randomCellBG(base, imgs) {

  // Reference the <table>
  var T = document.getElementById('mainTable');

  /* Collect all .cell into a NodeList and convert
  || it into an array
  */
  var cellArray = Array.from(T.querySelectorAll('.cell'));

  // map() the array; run a function on each loop...
  cellArray.map(function(cel, idx) {

    // Get a random number 1 - 9
    var ran = Math.round(Math.random() * imgs.length);

    /* Concatenate base and random number to form
    || a string of a url of an image
    ⍟ result: "images/Image_08.jpg"
    */
    var img = base + ran.toString();

    /* Assign that url as the value to the 
    || backgroundImage property of the .cell
    || in current iteration
    */
    cel.style.backgroundImage = 'url(' + img + ')';

  });

}

// Call randomCellBG
randomCellBG(base, imgs);
.cell {
  background-position: center;
}

td {
  background-color: grey
}
<!doctype html>
<html>

<head>
  <title>Random BG Table</title>

</head>

<body><br><br><br>
  <table width="300" height="200" border="1" id="mainTable">
    <tr>
      <td width="100" class="cell" id="cell1">&nbsp;</td>
      <td width="100" class="cell" id="cell2">&nbsp;</td>
      <td width="100" class="cell" id="cell3">&nbsp;</td>
    </tr>
    <tr>
      <td width="100" class="cell" id="cell4">&nbsp;</td>
      <td colspan='2' id="cell5">title</td>

    </tr>

  </table>
</body>

</html>
Community
  • 1
  • 1
zer00ne
  • 41,936
  • 6
  • 41
  • 68
  • Is there a way to images 1-9 named 01-09? It currently only seems to work if I drop the leading zero. It's not a big deal, just the way I like to name images. – dano Nov 19 '17 at 14:15
  • Sorry I must've neglected to emphasize that the array is an **array of numbers** (no quotes), your numbers are padded with a zero so you'll need to wrap each one in quotes because they are considered **strings**. – zer00ne Nov 19 '17 at 15:22
  • I tried adding quotes, but it didn't work. I must have missed something else. Now it's time to fix the random function to eliminate duplicates – dano Nov 19 '17 at 15:30
  • Your code with comments was perfectly undterstandable. Not sure why, but it worked when i change " to '. Also,I made .jpg a variable to be appended to the string making the url to make my array cleaner. – dano Nov 19 '17 at 15:59
  • Double quotes to single quotes made it work for you? That's very odd. Well if it resolves your problem don't forget to accept and/or upvote this answer. Happy coding. – zer00ne Nov 19 '17 at 16:43