Slider Progress
Introduction
With just a few lines, you can create a slider progress bar like this:
- 01
- 02
- 03
- 04
- 05
- 06
- 07
- 08
- 09
HTML And CSS
We can create the bar with <div> tags and CSS:
<divclass="splide"><divclass="splide__track"><ulclass="splide__list"><liclass="splide__slide">Slide01</li>...</ul></div><!-- Add the progress bar element --><divclass="my-slider-progress"><divclass="my-slider-progress-bar"></div></div></div>HTML
<div class="splide">
<div class="splide__track">
<ul class="splide__list">
<li class="splide__slide">Slide 01</li>
...
</ul>
</div>
<!-- Add the progress bar element -->
<div class="my-slider-progress">
<div class="my-slider-progress-bar"></div>
</div>
</div>
.my-slider-progress{background:#ccc;}.my-slider-progress-bar{background:greenyellow;height:2px;transition:width400msease;width:0;}CSS
.my-slider-progress {
background: #ccc;
}
.my-slider-progress-bar {
background: greenyellow;
height: 2px;
transition: width 400ms ease;
width: 0;
}
I recommend using the same value of the slider speed (options.speed) as the transition duration.
It makes the slider and the bar look more synchronized.
JavaScript
We can calculate the progress rate from the current index and the end index - ( current + 1 ) / ( end + 1 ).
Let's update the width of the bar via Splide#index and Controller#getEnd()
every time when the slider moves:
varsplide=newSplide('.splide');varbar=splide.root.querySelector('.my-slider-progress-bar');// Update the bar width:splide.on('mounted move',function(){varend=splide.Components.Controller.getEnd()+1;bar.style.width=String(100*(splide.index+1)/end)+'%';});splide.mount();JavaScript
var splide = new Splide( '.splide' );
var bar = splide.root.querySelector( '.my-slider-progress-bar' );
// Update the bar width:
splide.on( 'mounted move', function () {
var end = splide.Components.Controller.getEnd() + 1;
bar.style.width = String( 100 * ( splide.index + 1 ) / end ) + '%';
} );
splide.mount();
To settle the initial width, the example code also listens to the mounted event.
Tips
You can create a clickable progress bar with a few more steps:
- Compute a target index by a clicked position
- Move the slider by
Splide#go()
For accessibility, I recommend providing aria attributes, such as aria-controls, aria-valuenow and more. This document may help you.