Search code examples
htmlimagesizetimed

Changing the image size on image display that changes every few seconds


Cheers, I have this code for an image display that changes every few seconds but I can't figure out how to adjust the image size of each one, or how to make them all the same.

<!DOCTYPE html>

<html>
   <head>
      <title>change picture</title>
      <script type = "text/javascript">
          function displayNextImage() {
              x = (x === images.length - 1) ? 0 : x + 1;
              document.getElementById("img").src = images[x];
          }

          function displayPreviousImage() {
              x = (x <= 0) ? images.length - 1 : x - 1;
              document.getElementById("img").src = images[x];
          }

          function startTimer() {
              setInterval(displayNextImage, 3000);
          }

          var images = [], x = -1;
          images[0] = "image1.jpg";
          images[1] = "image2.jpg";
          images[2] = "image3.jpg";
      </script>
   </head>

   <body onload = "startTimer()">
       <img id="img" src="startpicture.jpg"/>
       <button type="button" onclick="displayPreviousImage()">Previous</button>
       <button type="button" onclick="displayNextImage()">Next</button>
   </body>
</html>

Thanks in advance!


Solution

  • It can be done with css. Wrap image in div, set it's dimensions and decide how to display image.

    If you want to stretch image to fit the div then set both width and height of image to 100%

    #img-box {
      width: 400px;
      height: 400px;
      border: 1px solid black;
     
    }
    #img-box img {
      max-width: 100%;
      max-height: 100%;
       
    }
    <!DOCTYPE html>
    
    <html>
    
    <head>
      <title>change picture</title>
      <script type="text/javascript">
        function displayNextImage() {
          x = (x === images.length - 1) ? 0 : x + 1;
          document.getElementById("img").src = images[x];
        }
    
        function displayPreviousImage() {
          x = (x <= 0) ? images.length - 1 : x - 1;
          document.getElementById("img").src = images[x];
        }
    
        function startTimer() {
          setInterval(displayNextImage, 3000);
        }
    
        var images = [],
          x = -1;
        images[0] = "https://upload.wikimedia.org/wikipedia/commons/a/a9/Bristol_MMB_%C2%AB42_River_Avon.jpg";
        images[1] = "https://upload.wikimedia.org/wikipedia/commons/1/19/Finsternis_Natur.jpg";
        images[2] = "https://upload.wikimedia.org/wikipedia/commons/8/8c/Black_CL.png";
      </script>
    </head>
    
    <body onload="startTimer()">
      <div id="img-box">
        <img id="img" src="https://upload.wikimedia.org/wikipedia/commons/0/03/Electricsheep-29142.jpg" />
      </div>
      <button type="button" onclick="displayPreviousImage()">Previous</button>
      <button type="button" onclick="displayNextImage()">Next</button>
    </body>
    
    </html>