IT Certificaions

Google Cloud Platform

Wednesday, March 14, 2012

Choose random image on page load



Let's suppose you are using following image tag...

<img src="images/home_1.jpg" id="imageSelecter" alt="Pick random image" />


Now add the following javascript code at the bottom of your page before closing of  HTML tag.

<script type="text/javascript">
       var images =new Array('images/home_1.jpg', 'images/home_2.jpg', 'images/home_3.jpg', 'images/home_4.jpg', 'images/home_5.jpg');
          
      var len = images.length;
     var random_no = Math.floor(len*Math.random());
     document.getElementById("imageSelecter").src = images[random_no];

</script>