0

I've written a function that should produce a random image from an array in Javascript. I'm wanting to execute the function with an html button. I've written the code but it doesn't work. The image should be directed to a flex box div.

Code

    var myImages= 
    ["https://picsum.photos/536/354","Images/IMG_4830.jpeg","Images/IMG_4338.jpeg",
    "Images/IMG_4096.JPG"];
    function randomImages(){
    var rnd = Math.floor(Math.random()*myImages.length);
    if(rnd == 0){
        rnd = 1;
    }
    var image = document.createElement("img");
    var div=document.getElementById("flex-box-create").src = myImages[rnd]
    div.appendChild(image)
    }

   button = <div><button class="btn btn-primary" id="image-Generator" 
   onclick="randomImages()">Click</button></div>

   thanks

1 Answers1

0

The source should be set on the image not the div, try this:

var image = document.createElement("img");
image.src = myImages[rnd];
var div = document.getElementById("flex-box-create");
div.appendChild(image);
Arleigh Hix
  • 9,990
  • 1
  • 14
  • 31