Jump to content

Random section background image on each visit/refresh

Recommended Posts

Hi all,

I'm trying to get the background image of a section (first section on a 7.1 home page) to randomly load a different image each time the user visits or refreshes the page - probably around 8 images in total.

I found the below code on an older post - sometimes it works, sometimes a new image loads but the original suddenly pops up over top of it.

Any suggestions that might iron out the bugs here would be appreciated.

document.addEventListener('DOMContentLoaded', function() {
  var images = [
].sort( () => .5 - Math.random() );
    var randImage = images[0];
    document.querySelector(".homepage article.sections section:first-child .section-background img").src = randImage;
    document.querySelector(".homepage article.sections section:first-child .section-background img").setAttribute("srcset", "");

Link to comment
  • Replies 2
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

On 5/15/2022 at 3:07 PM, tuanphan said:


We can achieve this with Gallery. Do you still need help on this?

Hi tuanphan,

Yes still looking for a suitable solution here.

Ideally I was hoping to achieve this using background images as I have a bit of content to go over top of the imagery. A gallery may be a workable option though if I cant get background images to work - how do you go about achieving random load of gallery images? (I don't want users to be able to scroll through other images either).


Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

  • Create New...

Squarespace Webinars

Free online sessions where you’ll learn the basics and refine your Squarespace skills.

Hire a Designer

Stand out online with the help of an experienced designer or developer.