Vérification de la préparation

Vous devriez maintenant être en mesure de comprendre et de reproduire le code suivant. Il s’agit d’un carrousel, qui défile soit automatiquement au bout de quelques secondes, soit lorsque l’utilisateur utilise la pagination.

Si ce n’est pas le cas, nous vous invitons à prendre le temps de lire les guides précédents et la documentation officielle plus en détail. Les formations étant très denses, c’est important pour qu’elle soit fluide et que nous puissions nous concentrer sur l’outil concerné et des sujets plus avancés, sans perdre de temps sur les bases de JavaScript.

La structure HTML :


<div id="slideshow">
<div id="slideshow-slides">
<div>
<figure><img src="image1.jpg" alt="" width="960" height="250"></figure>
</div>
<div>
<figure><img src="image2.jpg" alt="" width="960" height="250"></figure>
</div>
<div>
<figure><img src="image3.jpg" alt="" width="960" height="250"></figure>
</div>
</div>
<ul id="slideshow-pagination">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
</div>

view raw

slideshow.html

hosted with ❤ by GitHub

Le visuel CSS :


#slideshow {
width: 960px;
overflow-x: hidden;
}
#slideshow-slides {
display: flex;
}
#slideshow-pagination {
display: flex;
justify-content: center;
margin-top: 0;
padding-left: 0;
list-style: none;
}
#slideshow-pagination>li {
padding: 5px 10px;
cursor: pointer;
}

view raw

slideshow.css

hosted with ❤ by GitHub

Le comportement JavaScript :


interface SlideshowOptions {
delay?: number;
speed?: number;
}
export class Slideshow {
/** Delay between each automatic move */
delay: number;
/** Speed for one move */
speed: number;
/** Total of slides */
total: number;
/** Currently displayed slide */
current = 1;
/** Reference to the current timer */
timer: number;
/** Main wrapper element of all the slideshow */
elementMain: HTMLElement;
/** Wrapper element of all slides */
elementSlides: HTMLElement;
/** Pagination element */
elementPagination: HTMLElement;
/**
* Initializes a slideshow
* @param id Id of the main wrapper element of all the slideshow
* @param options Delay and speed options
*/
constructor(id: string, { delay = 5000, speed = 1000 }: SlideshowOptions = {}) {
this.delay = delay;
this.speed = speed;
/* Select HTML elements needed for running the slideshow module */
this.elementMain = document.getElementById(id) as HTMLElement;
this.elementSlides = this.elementMain.children[0] as HTMLElement;
this.elementPagination = this.elementMain.children[1] as HTMLElement;
/* Automatic dynamic configuration to adapt to all slideshows */
this.total = this.elementSlides.children.length;
/* Apply transition effects when moving */
this.elementSlides.style.transition = `transform ${speed}ms`;
this.elementSlides.addEventListener('transitionend', this.onTransitionEnd.bind(this));
/* Apply pagination data and listeners */
Array.from(this.elementPagination.children).forEach((element: HTMLElement, index) => {
element.dataset.page = `${index + 1}`;
});
this.elementPagination.addEventListener('click', this.onPaginationClick.bind(this));
/* Launches the first delay */
this.start();
}
/** Launches the automatic delay */
start() {
/* Stop any current timer to avoid concurrent timers */
this.stop();
/* Launches a new timer and then move */
this.timer = setTimeout(() => {
this.move();
}, this.delay);
}
/** Stops the current timeout */
stop() {
clearTimeout(this.timer);
}
/**
* Move to another slide
* @param next Position of the destination slide
*/
move(next = (this.current < this.total) ? (this.current + 1) : 1) {
/* Translate the slides container */
this.elementSlides.style.transform = `translateX(${(1 – next) * 100}%)`;
/* Update the new current position */
this.current = next;
/* The transitionend event (registered in constructor) will relaunch a new timer */
}
/** Transition listener handler */
onTransitionEnd(event: Event) {
/* Relaunch a new timer */
this.start();
}
/** Pagination listener handler */
onPaginationClick(event: Event) {
/* Checks the element clicked */
let target = event.target as HTMLElement;
if (target.tagName === 'LI') {
/* Stop the automatic delay as the user interacts */
this.stop();
/* Retrieves the page number in custom attributes */
let page = parseInt(target.dataset.page);
/* Move to the wanted slide */
this.move(page);
}
}
}

view raw

slideshow.ts

hosted with ❤ by GitHub

Finalement lancé avec :


import { Slideshow } from './slideshow.js';
/* Waiting for DOM to be ready */
document.addEventListener('DOMContentLoaded', () => {
new Slideshow('slideshow', { delay: 2000 });
});

view raw

main.ts

hosted with ❤ by GitHub

Vous voilà prêt·e pour la formation !

Revenir aux autres guides