Random picture and picture size

  1. question
    Okei so i copied this script and i was wondering how i can make all the picture the same size (decide how big they are going to be)
  2. question
    i also want it when every i press refresh it would change the picture. Now its just changing sometimes when i press refresh
  3. question
    i also want all the pictures in center (in the middle of the page)
<html>
<head>
    <title>Random</title>
    <link rel="stylesheet" href="random.css">
</head>
<body>
    <script type="text/javascript">
<!--
 var imlocation = "images/";
 var currentdate = 0;
 var image_number = 0;
 function ImageArray (n) {
   this.length = n;
   for (var i =1; i <= n; i++) {
     this[i] = ' '
   }
 }
 image = new ImageArray(13)
 image[0] = '1.jpg'
 image[1] = '2.jpg'
 image[2] = '3.jpg'
 image[3] = '4.jpg'
 image[4] = '5.jpg'
 image[5] = '6.jpg'
 image[6] = '7.jpg'
 image[7] = '8.jpg'
 image[8] = '9.jpg'
 image[9] = '10.jpg'
 image[10] = '11.jpg'
 image[11] = '12.jpg'
 image[12] = '13.jpg'
 image[13] = '14.jpg'
 image[14] = '15.jpg'
 image[15] = '16.jpg'
 image[16] = '17.jpg'
 image[17] = '18.jpg'
 image[18] = '19.jpg'
 var rand = 60/image.length
 function randomimage() {
    currentdate = new Date()
    image_number = currentdate.getSeconds()
    image_number = Math.floor(image_number/rand)
    return(image[image_number])
 }
 document.write("<img src='" + imlocation + randomimage()+ "'>");
//-->
</script>
</body>
</html>

Assuming that they all have the same aspect ratio, then you can simply set the dimensions in the CSS. If they are different aspects, it is more complicated and you’d be better asking a specific question in the HTML & CSS forum.

Also done with CSS. See https://css-tricks.com/centering-css-complete-guide/, if you need help with that.

Tank you so mutch for the tips:)

1 Like

I’ll move the thread to the JS forum as that is really a separate question from the CSS one which has been answered. The code you are using seems to do what you ask except that as its a random number you could get the same random number 2 or 3 times in a row on some occasions.

I guess you would need to save the image name each time in local storage or in a cookie and then check that image name from the storage/cookie when refreshed and if its the same as the new random generated image call the js again until you get a different image.

Also document.write should be avoided and you should be manipulating the dom instead. At present a user with js disabled gets nothing so you really need a default image on the page and then randomly change the source of that image and in that way someone always gets an image and not a blank screen.

I’ll leave the experts in the JS forum to offer a better solution.:slight_smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.