How to change image randomly in a webpage using JavaScript ?

0
900

In this tutorial, we are going to learn to change image randomly in a webpage using JavaScript.

We will defined fixed set of images which will be used in the webpage randomly after certain interval.

Watch this video for complete guidance :

Full Source Code

<style>
  body{
    background: #c3ece3;
  }
  .d-flex{
    display: flex;
    align-items: center;
    justify-content: center;
    height:100vh;
  }
  .figure{
    box-shadow: 1px 5px 10px #333;
    width:50%;
    margin: 0 auto;
  }
  .figure img{
    width:100%;
  }
</style>

<div class="d-flex">
  <figure class="figure">
  </figure>
</div>

<script type="text/javascript">
  var images = [
    'https://reeteshghimire.com.np/wp-content/uploads/2022/08/lottery.jpeg',
    'https://reeteshghimire.com.np/wp-content/uploads/2022/08/simple-image-carousel-using-bootstrap.png',
    'https://reeteshghimire.com.np/wp-content/uploads/2022/06/flying-plane-animation-using-html-css-1.jpg',
    'https://reeteshghimire.com.np/wp-content/uploads/2022/05/preview-image-before-upload-using-javascript.jpeg',
    'https://reeteshghimire.com.np/wp-content/uploads/2022/05/share-via-facebook-messenger-from-web.png',
    'https://reeteshghimire.com.np/wp-content/uploads/2022/03/confetti-party-popper-animation-using-javascript.png',
    'https://reeteshghimire.com.np/wp-content/uploads/2022/01/poonhill-trek.jpeg',
    'https://reeteshghimire.com.np/wp-content/uploads/2022/01/rara-trek.jpg'
  ];
  document.getElementsByClassName("figure")[0].innerHTML = '<img src="'+images[0]+'" id="image-preview">';
  setInterval(function(){
    changeImage();
  },2000);
  function changeImage(){
    index = parseInt((Math.random()*100)%images.length);
    document.getElementById('image-preview').setAttribute('src',images[index]);
  }
</script>

 

ALSO READ  Cool Trick : Like all Facebook posts at once

Comments are closed.