I'm trying to use appendchild to make a button that displays a random image from an array into a table, and will continue to display a new image on each click, but I need the newest image to stick to the top of the column, not the bottom. I tried to do this below but it appears to be an error.
function display_random_image1() {
var theImages = [{
src: "https://i.imgur.com/Ej3qKfd.png",
width: "120",
height: "120"
},
{
src: "https://i.imgur.com/P1i0O2m.png",
width: "120",
height: "120"
},
{
src: "https://i.imgur.com/FRaU0bc.png",
width: "120",
height: "120"
}
];
var preBuffer = [];
for (var i = 0, j = theImages.length; i < j; i++) {
preBuffer[i] = new Image();
preBuffer[i].src = theImages[i].src;
preBuffer[i].width = theImages[i].width;
preBuffer[i].height = theImages[i].height;
}
// create random image number
function getRandomInt(min, max) {
// return Math.floor(Math.random() * (max - min + 1)) + min;
imn = Math.floor(Math.random() * (max - min + 1)) + min;
return preBuffer[imn];
}
// 0 is first image, preBuffer.length - 1) is last image
var newImage = getRandomInt(0, preBuffer.length - 1);
// display the image
var targetContainer = document.getElementsByClassName("container");
targetContainer[0].appendChild(newImage);
targetContainer.insertBefore(newImage, targetContainer.childNodes[0]);
}
th,
td {
border: 1px solid black;
width: 100px
}
<table>
<tr>
<td>
<button id="initial" onclick="display_random_image1();">Beginning R</button>
</td>
</tr>
<tr>
<td>
<div class="container">
</tr>
</table>