Swiper JS - Change Section Background Color on Slide Change

I am using Swiper JS to make a slider and I want the background of the entire section to change color (ideally to a color set in a CMS so it can always correspond to a specific beer can color) when the slide changes to a new active slide.

I am basically trying to mimic the slider from Stone Brewing: https://www.stonebrewing.com/


Here is my site Read-Only: Webflow - Voyage Brewing

Live Build: https://voyage-brewing.webflow.io/

JS code: https://slater.app/projects/swiper-2d5cf26f-ce06-4aca-804d-483b440b89b5/pages/swiperjs

You would have to leverage the callback function in the API.

Here is a project that does something similar.

1 Like

Thank you so much! With some tweaking using that project and the help of chatGPT, I did the following to make it work:

  1. Added a custom attribute to my swiper slide with name: “beerColor” and value as a hex code inputted as a text variable from my CMS.
  2. I then added the following code:
beerSwiper.on("activeIndexChange", function () {
  let activeSlide = beerSwiper.slides[beerSwiper.activeIndex];
  let beerColor = activeSlide.getAttribute("beerColor");
  document.querySelector(".section-beer-slider").style.backgroundColor = beerColor;
});

.section-beer-slider is the class of the entire section, so with this code, it changes the background color to whatever is set by the beerColor attribute.

Woohoo, so happy!