Search code examples
javascripthtmldhtml

how to change the image when a page is refreshed using JavaScript?


I want to change the image when the page is refresh using html. I place my partial code here. i want a script or anything do change the image when the page gets refresh.. Please help me to do this using html ...

        <div class="one-image">
           <a href="">
            <img src="img/IMG_1035.jpg" class="giThumbnail" alt="Nightclubs"></a><h4 class="giDescription">
             Nightclubs</h4>
             </div>

the above image tag image is change every refresh.. please help me ..


Solution

  • I believe this would work, but all your images would have to be sequentially named, e.g. 1-100. Also note that the script was placed AFTER the IMG tag.

    <div class="one-image">            
      <a href="">             
        <img id="imgRand" src="" class="giThumbnail" alt="Nightclubs">
      </a>
      <h4 class="giDescription">              
        Nightclubs
      </h4>              
    </div> 
    
    <script language="javascript">
      // random number between 1 and 100
      var numRand = Math.floor(Math.random()*101);
      document.getElementById("imgRand").src = "img/IMG_"+numRand+".jpg";
    </script>
    

    The random formula in JS is:

    var random = Math.floor(Math.random() * (max - min + 1)) + min; 
    

    so if you only had 5 images between 135 and 140 your script would look like:

    var random = Math.floor(Math.random() * (140 - 135 + 1)) + 135; 
    

    If you wanted to change the image client-side, like a slideshow, just add a timer.

    <script language="javascript">
      function setImg(){
      // random number between 1 and 100
      var numRand = Math.floor(Math.random()*101);
      document.getElementById("imgRand").src = "img/IMG_"+numRand+".jpg";}
    
    
      // call it the first time
      setImg();
    
      // set an interval to change it every 30 seconds
      window.setInterval("setImg()",30000);
    </script>