Join

How to Create a Page Section With Dynamically Changing Background Images

  • Guides reflect how I’m currently using the solution for myself and my clients. 
  • If I don’t cover a specific feature, it implies I’m not using it.
  • If I don’t cover a specific setting, it implies the defaults are acceptable or the options are obvious.

For this solution, we will be using the free version of Elementor. 

  1. Add the Section widget to the desired page.
  2. Section > Layout > Content Width > Full Width
  3. Section > Layout > Height > Set the desired height.
  4. Section > Column > Advanced > Padding > 0
  5. Section > Column > Advanced > CSS ID > Enter something short, such as ‘dbs’ (dynamic background section), as you can always add a comment within your CSS for identification.
  6. Add the following code snippet using your preferred method for adding code to your website.
CSS
#dbs img.swiper-slide-image {
    width: 100%;
    height: 600px;
    object-fit:cover;
    object-position: center center;
    pointer-events: none;
}
  1. Add the Image Carousel widget to the container.
  2. Image Carousel > Content > Image Carousel > Images > Add the desired images to the carousel.
  3. Image Carousel > Content > Image Carousel > Image Size > Full
  4. Image Carousel > Content > Image Carousel > Slides to Show > 1
  5. Image Carousel > Content > Image Carousel > Navigation > None
  6. Image Carousel > Content > Additional Options > Autoplay > No
  7. Add the following code snippet using your preferred method for adding code to your website.
JavaScript
// DYNAMIC BACKGROUND SECTION
(function() {
    let parent = document.querySelector('.elementor-image-carousel');
    let images = parent.children;
    let frag = document.createDocumentFragment();
    while (images.length) {
        frag.appendChild(images[Math.floor(Math.random() * images.length)]);
    }
    parent.appendChild(frag);
}());

Now, you can refresh the page to see the random images displayed. Please see the video below for more information if you want to add elements that appear over/within the background section.

Note: Typical user behavior is not just sitting there refreshing the page, so if you see the same image displayed on subsequent refreshes, that won’t happen with regular website usage.

Video Tutorial

Youtube video