Skip to content

Random image from html on button click

I am trying to make a script that will take the images from one div element and put it to div rndmImage randomly on button click, I should see images when document is loaded, but the new div where images should go after click must be empty until click heapends. And I need only JavaScript, no jQuery, alse i can not change the html, and it has to work for any number of images. So if you have some ideas that would be great. Here’s my code.

window.addEventListener('load', start, false);

function start() {

    var butt = document.getElementsByTagName('button')[0];
    var rnImg = document.getElementsByClassName('ekran');
    var pictures = document.getElementsByTagName('img');
    var choose = Math.floor(Math.random()*pictures.length);

    butt.addEventListener('click', menjaj, false);

    function menjaj(e) {
        var new = e.button;

        var img = [];

        for(var i = 0; i< pictures.length; i++) {
            var dodaj = img[i];
            img.push(dodaj);
        }

        //ekran.src = 'slike/' + slike[izbor] + '.jpg';
    }


    

}
<body>
 <div class="wrapper">
  <div>
    <img src="slike/leto1.jpg" alt="leto1">
    <img src="slike/leto2.jpg" alt="leto2">
    <img src="slike/leto3.jpg" alt="leto3">
    <img src="slike/leto4.jpg" alt="leto4">
    <img src="slike/leto5.jpg" alt="leto5">
    <img src="slike/leto6.jpg" alt="leto6">
    <img src="slike/leto7.jpg" alt="leto7">
    <img src="slike/leto8.jpg" alt="leto8">
    <img src="slike/leto9.jpg" alt="leto9">
  </div>
   <div>
    <button type="button">choose</button>
   </div>
  <div class="rndmImage"></div>
 </div>
</body>

Answer

This is a working snippet of your code:

window.addEventListener('load', start, false);

function start () {
    var butt = document.getElementsByTagName('button')[0];
    var rnImg = document.getElementsByClassName('rndmImage')[0]; //Change selector to existing class and select the first (the only) one
    var pictures = document.getElementsByTagName('img');

    butt.addEventListener('click', menjaj, false);

    function menjaj (e) {
        // var new = e.button;// 'new' is reserved word in JS, you can't use it as variable name
        // var btn = e.button;// but this line is useless
        var choose = Math.floor(Math.random() * pictures.length); //better move this line inside this function to get rundom image every button clicks

        var img = document.createElement('img'); //creates new img tag
        img.src = pictures[choose].src;
        rnImg.innerHTML = ''; //to delete previous image
        rnImg.appendChild(img);
        // var img = []; //useless lines of code

        // for(var i = 0; i< pictures.length; i++) {
        //     var dodaj = img[i];
        //     img.push(dodaj);
        // }

        //ekran.src = 'slike/' + slike[izbor] + '.jpg';
    }
}