Pick random image

For Anki question

by OjisanSeiuchi

HTML

<html>

  <body>
    <!-- wrap all your image fields in a div with this format img1, img2, img3, etc. -->
    <div id="img1">
      <!-- instead of an img tag, replace each of these with a field reference -->
      <img src="https://source.unsplash.com/random/200x200?sig=1" />
    </div>
    <div id="img2">
     <!-- same here use a field reference -->
      <img src="https://source.unsplash.com/random/200x200?sig=2" />
    </div>
    <div id="img3">
    <!-- and here -->
      <img src="https://source.unsplash.com/random/200x200?sig=3" />
    </div>
  </body>

</html>

JavaScript

// all the divs whose id begins with "img"
var imgDivs = document.querySelectorAll('[id^="img"]');
let imgCount = imgDivs.length;
// hide all of them
for( let i = 0; i < imgCount; i++) {
	imgDivs[i].style.display = "none";
}
// unhide one random img element
let randImgIdx = Math.floor(Math.random() * imgCount);
imgDivs[randImgIdx].style.display = "block";