Page 1 of 1
How do I randomly change the background image on reload?
Posted: Mon Aug 22, 2016 7:01 am
by simonmlewis
Code: Select all
<style>
.home-banner
{
position: relative;
/* The image used */
background-image: url('../images/banner-home.jpg');
/* Full height */
height: 83%;
/* Create the parallax scrolling effect */
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
}
</style>
The idea is that each time the page loads, it can load a different image, maybe from a set of three.
I've seen how to do when the image is directly in the DIV, but not as a background.
And coding the background-image code into the HTML is bad-form. So is there a good way to do it?
Re: How do I randomly change the background image on reload?
Posted: Mon Aug 22, 2016 8:04 am
by requinix
Either
a) Use a random path in the CSS itself.
b) Point the CSS to a PHP script and have
it randomize the image.
The latter is probably your best bet.
Code: Select all
background-image: url('../images/banner-random.php');
Code: Select all
<?php
$images = array(
'banner-home.jpg',
...
);
$image = $images[array_rand($images)];
$filename = __DIR__ . '/' . $image;
header('Content-Type: image/jpeg');
header('Content-Length: ' . filesize($filename));
readfile($filename);