Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Refreshing page with a new image [duplicate]

I currently have a stagnant image on my site:

    <!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="/stylesheets/normalize.css" media="all" rel="stylesheet" />
  <link href="/stylesheets/master.css" media="all" rel="stylesheet" />

<script>
window.onload = function () {

    var images = [],
        i=1, indexImages = true,
        prefix = '../image/',
        extension = '.jpg';

    while (indexImages) {
        var a = new XMLHttpRequest(); a.open('GET', prefix+i+extension, false); a.send();

        if (a.status != 404) { i += 1; images.push(prefix+i+extension); } else {
            indexImages = false;

            localStorage['backgroundIndex'] = !localStorage['backgroundIndex']?0:+localStorage['backgroundIndex']+2>images.length?0:+localStorage['backgroundIndex']+1;
            document.body.style.backgroundImage =  'url(' + images[+localStorage['backgroundIndex']] + ')';

        }
    }

}
</script>

<style>
body {
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-position: center;
    background-color: black;

    border-bottom: 8px solid  #7D8A28;
}

</style>

</head>
<body>
  <section id="card">
  </section>
</body>
</html>

It's just that I want it to be a different image each time the page refreshes, so it auto changes to 2.jpg, 3.jpg, 10.jpg, whatever. (There are hundreds to choose from)

Could someone help me out with a solution? I'm not very good at this, and this is my first site.

Thanks.

like image 601
Brian Fitzpatrick Avatar asked Nov 01 '22 05:11

Brian Fitzpatrick


1 Answers

I don't think CSS alone can do this, here's an answer:

Random

window.onload = function () {
    var images = [
        'image/1.png',
        'image/2.png',
        'image/3.png',
        'image/4.png'
    ];

    document.body.style.backgroundImage = 'url(' + images[Math.floor(Math.random()*images.length)] + ')';
}

This will load a random image every time you visit the page.


Specified Order

To load them in sequential order: First time image1, second time image2. The images don't need even have a number for this to work just fine. Do:

window.onload = function () {
    var images = [
        'image/A.png',
        'image/B.png',
        'image/C.png',
        'image/D.png'
    ];

    localStorage['backgroundIndex'] = !localStorage['backgroundIndex']?0:+localStorage['backgroundIndex']+2>images.length?0:+localStorage['backgroundIndex']+1;

    document.body.style.backgroundImage =  'url(' + images[+localStorage['backgroundIndex']] + ')';
}

Generating the Array (ONLY IF YOUR IMAGES HAVE A NUMBER AT THE END)

This will automatically generate the array for you and you don't have to provide the amount of images

window.onload = function () {

    var images = [],
        i = 1,
        prefix = 'image/',
        extension = '.png',
        max = 1000;

    function index() {
        var a = new XMLHttpRequest();
        a.open('GET', prefix + i + extension, false);
        a.send();
        a.onreadystatechange = function () {
            if (a.readyState === 4) {
                if (a.status != 404) {
                    i += 1;
                    images.push(prefix + i + extension);
                    i < max ? index();
                } else {}

                localStorage['backgroundIndex'] = !localStorage['backgroundIndex'] ? 0 : +localStorage['backgroundIndex'] + 2 > images.length ? 0 : +localStorage['backgroundIndex'] + 1;
                document.body.style.backgroundImage = 'url(' + images[+localStorage['backgroundIndex']] + ')';

            }

        };
    }

    index();
}


Most versatile solution

If you have PHP, this is probably the best solution in terms of working in many cases. But you really don't want to use PHP if you can avoid it. It will get all images in a directory to generate the array:

window.onload = function () {
    var images = (JSON.parse("<?=scandir('../images')?>")||[]).filter(function (a) {  return ['.', '..'].indexOf(a) < 0;  });

    document.body.style.backgroundImage =  'url(' + images[+localStorage['backgroundIndex']] + ')';

};
like image 188
Downgoat Avatar answered Nov 09 '22 14:11

Downgoat