I have working javascript code that produces multiple random images in to one DIV.
I have tried a few attempts to display each random image in a separate DIV but with no luck. I got "close" but no success.
Here is working code:
<style>.onetwothreefour { width: 25%; display: inline-block;}</style>
<script>
function displayNow() {
var images = ["00.png","01.png","02.png","03.png","04.png","05.png","06.png"];
var selectedIndices = []
while (selectedIndices.length < 4) {
var index = images[Math.floor(Math.random() * images.length)]
if (selectedIndices.indexOf(index) == -1) {
selectedIndices.push(index)
}
}
for (i = 0; i < selectedIndices.length; i++) {
var img = document.createElement("img");
img.src = "imagesfolder/" + selectedIndices[i]
img.className = "onetwothreefour"
var src = document.getElementById("images");
src.appendChild(img);
}
}
</script>
</head>
<body onLoad="displayNow();">
<div id="images"><!-- Images --></div>
<!-- the above works fine but I would like the result below -->
<div class="container"><div class="row">
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
<div id="" class=""><img src="" id="" class=""></div>
</div></div>
Note: I have jquery and bootstrap loaded.
I appreciate any help.
This approach will be more efficient.
Explaination : The
while
loop runs for four times. A random index is generated, and the element is removed fromimages
array, and pushed intoselectedIndices
array.You’re already using
createElement()
to build theimg
elements – you can use the same method to create a newdiv
, add the childimg
to it, then append that to the DOM. Try this: