Hi all, I’m trying to create a rotating banner on my website so that every time the page reloads, a new hero image appears, kind of like what’s happening here, but with the full background image.
So far I’ve been able to use a CMS list limited to 1 image that randomly shuffles so it shows a different image from the collection everytime, but when the page is stretched wider than the image it will start to distort if I also limit the height. This also has the downside that it doesn’t really stay intact when the browser is narrowed, but I haven’t gotten to editing the other breakpoints for mobile devices yet.
So far solutions would seem to be either to get the image to constrain proportions within the section it’s in- maybe somebody has some ideas?- or to use the section background image, with the downside of the latter being that I lose the feature of the rotating header.
The only problem I have is that you need to use an image element. I’m still searching for the background solution. I’m not a code master so yea Btw there’s a CSS code you can use to make an image element act as a background.
How the structure works:
1. A div with a class > section > 100vh or whatever you want
2. Image element inside with ID randomImage
3. Script before the closing body tag
Here’s the script
<script>
function getRandomImage() {
var images = ['urloftheimagehere', 'urloftheimagehere', 'urloftheimagehere'];
var image = images[Math.floor(Math.random()*images.length)];
return image;
}
function displayRandomImage() {
var htmlImage = document.getElementById("randomImage");
htmlImage.src = getRandomImage();
}
displayRandomImage();
</script>
If you have more questions feel free to reach out.