Random photo with javascript

Asked

Viewed 663 times

1

Colleagues

I would like each time the user accesses the site, a different image appears. I know how to do with PHP, but in this case I would like to do with javascript. I believe that the Math.(), but I don’t know much javascript. I tried to do it this way, but it didn’t 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>

2 answers

2


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

An alternative would be to call the script just below the div, auto-invoke 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>

  • 1

    Perfect Marceloboni. Thank you!

0

It is possible to generate using an adapted Fisher-Yates with an array of images:

var imglis = ["http://puu.sh/DpIbK/7c14bc67e1.jpg",
  "http://puu.sh/DpIcD/9438c374f0.jpg",
  "http://puu.sh/DpIdc/b67b518ead.jpg",
  "http://puu.sh/DpIdq/5747748430.jpg",
  "http://puu.sh/DpIdE/54a196c849.jpg",
  "http://puu.sh/DpIdS/b8b3863be2.jpg",
  "http://puu.sh/DpIe9/68de9bc09a.jpg",
  "http://puu.sh/DpIep/b76855cd03.jpg",
  "http://puu.sh/DpIeC/7d41b98b20.jpg",
  "http://puu.sh/DpIeV/207954672c.jpg",
  "http://puu.sh/DpIfp/5299a8a2f8.jpg"]; 

function imagem_aleatoria() {
  var p, n, tmp, destino = document.querySelector('#imgdest');
  var img_len = imglis.length;
  for (p = img_len; p;) {
    n = Math.random() * p-- | 0;
    tmp = imglis[n];
    imglis[n] = imglis[p];
    imglis[p] = tmp;
  }
  destino.src = imglis[0];
}

Testing: https://jsbin.com/pujivov/edit?html,js,output

Browser other questions tagged

You are not signed in. Login or sign up in order to post.