Carousel Progress
Introduction
With just a few lines, you can create a carousel 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:
<
section
class
=
"splide"
aria-label
=
"..."
>
<
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-carousel-progress"
>
<
div
class
=
"my-carousel-progress-bar"
>
<
/
div
>
<
/
div
>
<
/
section
>
HTML
<section class="splide" aria-label="..."> <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-carousel-progress"> <div class="my-carousel-progress-bar"></div> </div> </section>
.my-carousel-progress
{
background
:
#ccc
;
}
.my-carousel-progress-bar
{
background
:
greenyellow
;
height
:
2
px
;
transition
:
width
400
ms
ease
;
width
:
0
;
}
CSS
.my-carousel-progress { background: #ccc; } .my-carousel-progress-bar { background: greenyellow; height: 2px; transition: width 400ms ease; width: 0; }
I recommend using the same value of the carousel speed (options.speed
) as the transition duration.
It makes the carousel 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 carousel moves:
var
splide
=
new
Splide
(
'.splide'
)
;
var
bar
=
splide
.
root
.
querySelector
(
'.my-carousel-progress-bar'
)
;
// Updates the bar width whenever the carousel moves:
splide
.
on
(
'mounted move'
,
function
(
)
{
var
end
=
splide
.
Components
.
Controller
.
getEnd
(
)
+
1
;
var
rate
=
Math
.
min
(
(
splide
.
index
+
1
)
/
end
,
1
)
;
bar
.
style
.
width
=
String
(
100
*
rate
)
+
'%'
;
}
)
;
splide
.
mount
(
)
;
JavaScript
var splide = new Splide( '.splide' ); var bar = splide.root.querySelector( '.my-carousel-progress-bar' ); // Updates the bar width whenever the carousel moves: splide.on( 'mounted move', function () { var end = splide.Components.Controller.getEnd() + 1; var rate = Math.min( ( splide.index + 1 ) / end, 1 ); bar.style.width = String( 100 * rate ) + '%'; } ); 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 carousel by
Splide#go()
For accessibility, I recommend providing aria attributes, such as aria-controls
, aria-valuenow
and more. This document may help you.