Back

Technologies:

javascriptjavascript
csscss
avatar
Tolerim
a day ago

How can I properly set the duration for filling the progress bar in SwiperJS based on the data-swiper-autoplay property?

While exploring the swiper js pin - https://codepen.io/yassersharaf/pen/qBJoWGY, I came across an issue where the CSS code fixes the progress bar color fill for 2 seconds. However, I want the progress bar to be filled dynamically based on the value of the data-swiper-autoplay attribute of the current slide. The following code is responsible for the current progress bar color fill:

.swiper-pagination-bullet-active::before {
  background-color: red;
  -webkit-animation: slide-progress 2s cubic-bezier(0.3, 0, 0.3, 1) forwards;
  animation: slide-progress 2s cubic-bezier(0.3, 0, 0.3, 1) forwards;
}
How can I modify this code so that the progress bar color fill matches the value of data-swiper-autoplay attribute of each slide?

Answers(1)
avatar
Tolerim
a day ago
Verified Answer
To change the progress bar color fill according to the value of the data-swiper-autoplay property of the current slide, you can add a bit of JavaScript code to dynamically change the CSS styles. Here is an example of how you can achieve this:
var swiper = new Swiper('.swiper-container', {
    pagination: {
        el: '.swiper-pagination',
        type: 'progressbar',
    },
    on: {
        slideChange: function() {
            // get the current slide
            var currentSlide = this.slides[this.activeIndex];
            
            // get the value of "data-swiper-autoplay" property
            var autoplayValue = currentSlide.getAttribute('data-swiper-autoplay');
            
            // set the background-color of progress bar based on the autoplayValue
            var progressBar = document.querySelector('.swiper-pagination-bullet-active').querySelector('::before');
            progressBar.style.backgroundColor = autoplayValue;
            
            // start the progress animation with the value specified in "data-swiper-autoplay"
            progressBar.style.animation = 'slide-progress ' + autoplayValue + 's cubic-bezier(0.3, 0, 0.3, 1) forwards';
        }
    }
});
In this code example, we are using the on.slideChange event of Swiper.js to listen for slide changes. Whenever the slide changes, we get the current slide and its "data-swiper-autoplay" attribute value. We then set the background-color of the progress bar to this value and start the progress animation with the same value. This way, the progress bar will be dynamically filled according to the "data-swiper-autoplay" value of the current slide.
;