Random photo with javascript

1

Colleagues

I would like every time the user accesses the site, a different image appears. I know how to do with PHP, however in this case I would like to do with javascript. I believe the Math.random () , but I do not know much javascript. I tried to do it that way, but it did not work:

<script type="text/javascript">
   function aleatorio(){
     img[0] = "ciadeli.jpg";
     img[1] = "ninashoes.jpg";
     img[2] = "odonto.jpg";
     var mudar = Math.floor(Math.random()*img.length);
     document.getElementById("aleatorio").innerHTML = "<img src='portifolios/"+img[mudar]+"'>";
   }
  </script>

<div id="aleatorio" onload="aleatorio()"></div>
    
asked by anonymous 13.05.2017 / 19:17

1 answer

2

Your almost function works the way it is, the only problem is how it invokes it, the onload event should only be assigned to elements that consume external resources, such as: frames, images , and scripts. A div is not considered as an external element, it is loaded as a part of the body, so onload does not apply to it.

An alternative would be to call the script just below the div, auto invoking the function:

img {width: 200px;}
<div id="aleatorio"></div>
<script type="text/javascript">
  (function() {
    // Necessário declarar a variável img 
    var img = ["http://orig14.deviantart.net/45e6/f/2016/046/c/c/cc2df80f7717e34ef6373cb48f11196a-d9rv8ct.gif", "https://i.giphy.com/JJh1zuwzcJlQs.gif", "https://i.giphy.com/Jd7Y8GCSKKzlK.gif"];
    var mudar = Math.floor(Math.random() * img.length);
    document.getElementById("aleatorio").innerHTML = "<img src='" + img[mudar] + "'>";
  })();
</script>
    
13.05.2017 / 20:02