skip to Main Content

If i had a folder books_images with set of images

- books_images 
-- 1.jpg
-- 2.jpg
-- 3.jpg
-- 4.jpg
-- 5.jpg
-- 6.jpg

How can i iterate through this folder and pick up (number) of images in random way each time and combine all into one single image to be used as background for index.html

just like this one and if you make refresh, it makes different sequences in images.

enter image description here

2

Answers


  1. if you have for example 20 images in your folder , you should give a random number between 0 and 20 and set it as a variable at end of your folder directory , for example :

    let myRandomNumber = Math.random() * 20;
    let img = document.querySelector("img");
    let randomPath = '/your-folder-name/' + myRandomNumber + '.jpg';
    img.src = randomPath;
    

    if you want to iteration through a folder and combine a random number of image :

    let images = document.querySelectorAll("img");
    let path = '/your-folder-path/'
    
    const myArr = []
    while(myArr.length <= images.length){
        let randomNumber = Math.floor(Math.random() * images.length);
        if (myArr.indexOf(randomNumber) === -1) {
            myArr.push(randomNumber);
        }
    }
    
    if(images){
        images.forEach((img , index) => {
            img.src = path + myArr[index]
        })
    }
    
    Login or Signup to reply.
  2. This little demo works, I have only done 4 images from a selection of 6. You can amend the calls to ‘randomNo’ as needed. You would need to expand the css rules to fit the number of images you want to display at once.

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Background Demo</title>
    
    </head>
    <body onload="randomBackground()">
    
      <script>
        function randomNo(min, max) {
            min = Math.ceil(min);
            max = Math.floor(max);
            return Math.floor(Math.random() * (max - min) + min);
        }
        function randomBackground() {
            var element = document.createElement('style'), sheet;
            document.head.appendChild(element); //create a stylesheet
            sheet = element.sheet;
    
            var styles = 'body {';
            styles += 'background: url(images/'+randomNo(1,6)+'.jpg), url(images/'+randomNo(1,6)+'.jpg), url(images/'+randomNo(1,6)+'.jpg), url(images/'+randomNo(1,6)+'.jpg);'; //Build the random background
            styles += 'background-repeat: no-repeat, no-repeat, no-repeat, no-repeat;'
            styles += 'background-size: 50vw 50vh, 50vw 50vh, 50vw 50vh, 50vw 50vh;'
            styles += 'background-position: 0 0, 50vw 0, 0 50vh, 50vw 50vh;'
            styles += '}';
    
            sheet.insertRule(styles, 0); //add rule to new sheet
    
        }
      </script>
    </body>
    </html>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search