HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URLs added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by esm.sh, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ESM usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<section class="section carrousel">
<div class="container padding--0">
<h2 id="xxx" class="h2 carrousel__title">Carrousel A11Y</h2>
<div class="carrousel__container" data-carousel>
<div class="carrousel__main carrousel-content">
<div class="carrousel-content__list-slide" id="slider-carrousel-content" data-carousel-list>
<div class="carrousel-content__slide" data-carousel-list-inner>
<div class="carrousel-content__container" data-carousel-list-item>
<div class="carrousel-content__content">
<p class="carrousel-content__title">Slide 1</p>
<img src="https://www.naturephotographie.com/wp-content/uploads/2022/10/Autumnal-Efficiency.jpg" alt="@TODO : Ne pas oublier de mettre un alt" class="carrousel-content__img" width="100%" height="346">
</div>
</div>
<div class="carrousel-content__container" data-carousel-list-item>
<div class="carrousel-content__content">
<p class="carrousel-content__title">Slide 2</p>
<img src="https://img.freepik.com/photos-gratuite/route-etroite-dans-champ-herbeux-vert-entoure-arbres-verts-soleil-eclatant-arriere-plan_181624-9968.jpg?w=2000" alt="@TODO : Ne pas oublier de mettre un alt" class="carrousel-content__img" width="100%" height="346">
</div>
</div>
<div class="carrousel-content__container" data-carousel-list-item>
<div class="carrousel-content__content">
<p class="carrousel-content__title">Slide 3</p>
<img src="https://thumbs.dreamstime.com/b/belle-for%C3%AAt-tropicale-%C3%A0-l-itin%C3%A9raire-am%C3%A9nag%C3%A9-pour-amateurs-de-la-nature-de-ka-d-ang-36703721.jpg" alt="@TODO : Ne pas oublier de mettre un alt" class="carrousel-content__img" width="100%" height="346">
</div>
</div>
<div class="carrousel-content__container" data-carousel-list-item>
<div class="carrousel-content__content">
<p class="carrousel-content__title">Slide 4</p>
<img src="https://img.freepik.com/photos-gratuite/prise-vue-au-grand-angle-seul-arbre-poussant-sous-ciel-assombri-pendant-coucher-soleil-entoure-herbe_181624-22807.jpg" alt="@TODO : Ne pas oublier de mettre un alt" class="carrousel-content__img" width="100%" height="346">
</div>
</div>
</div>
</div>
</div>
<div class="slider-nav" data-carousel-arrows>
<!-- aria-describedby="xxx" xxx = id du titre-->
<button class="slider-nav__arrow slider-nav__arrow--left"
data-carousel-arrow-prev
aria-controls="slider-carrousel-content"
aria-describedby="xxx">
<span class="fa-solid fa-chevron-left" aria-hidden="true"></span>
<span class="visuallyhidden">Précédent</span>
</button>
<button class="slider-nav__arrow slider-nav__arrow--right"
aria-controls="slider-carrousel-content"
aria-describedby="xxx"
data-carousel-arrow-next>
<span class="fa-solid fa-chevron-right" aria-hidden="true"></span>
<span class="visuallyhidden">Suivant</span>
</button>
</div>
</div>
</div>
</section>
@import "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css";
.visuallyhidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
white-space: nowrap;
}
.carrousel {
padding: 20px 0;
@media screen and (min-width: 1024px) {
padding: 90px 0;
}
.container {
padding: 0;
}
&__title {
padding: 0 40px;
margin-bottom: 10px;
}
&__container {
position: relative;
--slides-per-frame: 1;
--animation-type: 'translate';
--animation-duration: 5000;
}
.slider-nav {
position: absolute;
z-index: 1;
top: 0;
left: 0;
display: flex;
align-items: center;
justify-content: space-between;
width: 85%;
padding: 0 13%;
@media screen and (min-width: 1024px) {
width: 44%;
display: inline-flex;
top: 10px;
left: 40%;
transform: translateX(-50%);
flex-direction: row;
}
&__arrow {
border: none;
margin: 0;
letter-spacing: 0 !important;
word-spacing: 0 !important;
line-height: 1 !important;
background: none;
font-size: 2rem;
&:focus,
&:hover {
background: none;
color: #000080;
}
}
}
&__main {
overflow: hidden;
}
}
.carrousel-content {
margin-top: 30px;
@media screen and (min-width: 1024px) {
margin-top: 73px;
}
&__slide {
display: flex;
flex-direction: row;
flex-wrap: nowrap;
transform: translateX(0px);
transition: transform .5s ease-in-out;
}
&__container {
z-index: 1;
width: 85%;
flex-shrink: 0;
background: color('grey', 'light');
//padding: 0 40px;
justify-content: center;
margin-right: auto;
margin-left: 10%;
}
&__content {
padding-top: 53px;
@media screen and (min-width: 1024px) {
padding-top: 135px;
padding-bottom: 100px;
}
&__container {
display: flex;
flex-direction: column;
gap: 50px;
width: 100%;
}
}
&__title {
margin-top: 0;
margin-bottom: 23px;
font-size: 50px;
line-height: 50px;
margin-left: 25%;
@media screen and (min-width: 800px) {
margin-left: 35%;
}
}
}
'use strict';
class A11yHelpers
{
static key() {
return {
ALT: 'Alt',
SHIFT: 'Shift',
ENTER: 'Enter',
TAB: 'Tab',
SPACE: ' ',
UP: 'ArrowUp',
DOWN: 'ArrowDown',
LEFT: 'ArrowLeft',
RIGHT: 'ArrowRight',
HOME: 'Home',
END: 'End',
PAGE_UP: 'PageUp',
PAGE_DOWN: 'PageDown',
DEL: 'Delete',
ESC: 'Escape',
};
}
static isFocusable(element) {
if (element.tabIndex < 0) {
return false;
}
if (element.tabIndex === 0) {
return true;
}
if (element.disabled) {
return false;
}
switch (element.nodeName) {
case 'A':
return !!element.href && element.rel !== 'ignore';
case 'INPUT':
return element.type !== 'hidden';
case 'BUTTON':
case 'SELECT':
case 'TEXTAREA':
return true;
case 'AUDIO':
case 'VIDEO':
return true;
default:
return false;
}
}
static getFocusableNodes() {
return [
'a',
'button',
'input',
'select',
'textarea',
'[tabindex]',
'audio[controls]',
'video[controls]',
];
}
static listFocusableElements(element) {
if (element === undefined) {
return [];
}
const focusableElements = this.getFocusableNodes();
return Array.from(element.querySelectorAll(focusableElements)).filter((item) => {
return this.isFocusable(item);
});
}
static hasAccessibleName(element) {
if (element.nodeName === 'BUTTON') {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasTitle(element)
|| this.hasInnerText(element);
}
if (element.nodeName === 'INPUT') {
if (['submit', 'reset', 'button'].includes(element.type)) {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasValue(element)
|| this.hasTitle(element);
} else if (element.type === 'image') {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasAlternative(element)
|| this.hasTitle(element);
} else {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasLabel(element)
|| this.hasTitle(element)
|| this.hasPlaceholder(element);
}
}
if (element.nodeName === 'FIELDSET') {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasLegend(element)
|| this.hasTitle(element);
}
if (element.nodeName === 'OUTPUT') {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasInnerText(element)
|| this.hasTitle(element);
}
if (element.nodeName === 'SUMMARY') {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasInnerText(element)
|| this.hasTitle(element);
}
if (element.nodeName === 'FIGURE') {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasFigureCaption(element)
|| this.hasTitle(element);
}
if (element.nodeName === 'IMG') {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasAlternative(element)
|| this.hasTitle(element);
}
if (element.nodeName === 'TABLE') {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasTableCaption(element)
|| this.hasTitle(element);
}
if (element.nodeName === 'A') {
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasInnerText(element)
|| this.hasTitle(element);
}
return this.hasAriaLabelledBy(element)
|| this.hasAriaLabel(element)
|| this.hasTitle(element);
}
static hasInnerText(element) {
return element.innerText !== '';
}
static hasTitle(element) {
return element.getAttribute('title') !== undefined
&& element.getAttribute('title') !== '';
}
static hasValue(element) {
return element.getAttribute('value') !== undefined
&& element.getAttribute('value') !== '';
}
static hasLabel(element) {
return element.getAttribute('id') !== undefined
&& element.getAttribute('id') !== ''
&& document.querySelector('label[for="' + element.getAttribute('id') + '"]') !== null
&& document.querySelector('label[for="' + element.getAttribute('id') + '"]').innerText !== '';
}
static hasPlaceholder(element) {
return element.getAttribute('placeholder') !== undefined
&& element.getAttribute('placeholder') !== '';
}
static hasAlternative(element) {
return element.getAttribute('alt') !== undefined
&& element.getAttribute('alt') !== '';
}
static hasTableCaption(element) {
return element.querySelector('caption') !== null
&& element.querySelector('caption').innerText !== '';
}
static hasFigureCaption(element) {
return element.querySelector('figcaption') !== null
&& element.querySelector('figcaption').innerText !== '';
}
static hasLegend(element) {
return element.querySelector('legend') !== null
&& element.querySelector('legend').innerText !== '';
}
static hasAriaLabel(element) {
return element.getAttribute('aria-label') !== undefined
&& element.getAttribute('aria-label') !== '';
}
static hasAriaLabelledBy(element) {
return element.getAttribute('aria-labelledby') !== undefined
&& element.getAttribute('aria-labelledby') !== ''
&& document.getElementById(element.getAttribute('aria-labelledby')) !== null;
}
static hasAriaRoledescription(element) {
return element.getAttribute('aria-roledescription') !== undefined
&& element.getAttribute('aria-roledescription') !== '';
}
static hasAriaExpanded(element) {
return element.getAttribute('aria-expanded') === 'true'
|| element.getAttribute('aria-expanded') === 'false';
}
static waitForElement(selector) {
return new Promise(resolve => {
if (document.querySelector(selector)) {
return resolve(document.querySelector(selector));
}
const observer = new MutationObserver(mutations => {
if (document.querySelector(selector)) {
resolve(document.querySelector(selector));
observer.disconnect();
}
});
observer.observe(document.body, {
childList: true,
subtree: true
});
});
}
static getCookie(name) {
const cookie = document.cookie.split('; ').find(item => item.startsWith(name + '='));
return cookie ? cookie.split('=')[1] : false;
}
static setCookie(name, value) {
const d = new Date();
d.setTime(d.getTime() + (365 * 24 * 60 * 60 * 1000));
document.cookie = [
name + '=' + value,
'expires=' + d.toUTCString(),
'path=/',
'SameSite=Lax',
].join(';');
}
}
/**
* @TODO : autoplay (reduced-motion)
*/
/**
* @class Carousels' list
*/
class A11yCarousels {
/**
* @desc Creates an instance of carousels' list
* @constructor
* @param {object} params
*/
constructor(params) {
const defaultParams = {
settingsActiveClass: 'is-active',
settingsAutoplay: 'data-carousel-autoplay',
carousel: 'data-carousel',
carouselList: 'data-carousel-list',
carouselListInner: 'data-carousel-list-inner',
carouselListItem: 'data-carousel-list-item',
carouselSubList: 'data-carousel-sub-list',
carouselSubListInner: 'data-carousel-sub-list-inner',
carouselSubListItem: 'data-carousel-sub-list-item',
carouselIndex: 'data-carousel-index',
controlsPlayer: 'data-carousel-player',
controlsPlay: 'data-carousel-player-play',
controlsPause: 'data-carousel-player-pause',
controlsBullets: 'data-carousel-bullets',
controlsBullet: 'data-carousel-bullet',
controlsArrows: 'data-carousel-arrows',
controlsArrowPrev: 'data-carousel-arrow-prev',
controlsArrowNext: 'data-carousel-arrow-next',
};
this.errorMessage = A11yCarousels.name + ' : ';
this.params = this.checkParams({...defaultParams, ...params});
/** @var {A11yCarousel[]} */
this.list = [];
document.querySelectorAll('[' + this.params.carousel + ']').forEach((listElement) => {
const item = new A11yCarousel(this.params, listElement);
this.list.push(item);
});
}
/**
* @desc Check all needed params and throw errors
*/
checkParams(params) {
if (params.settingsActiveClass === '') {
throw new Error(this.errorMessage + 'active class cannot be empty');
}
Object.keys(params).map((param, i, v) => {
if (param !== 'settingsActiveClass') {
const attr = params[param];
if (!attr.startsWith('data-')) {
throw new Error(this.errorMessage + 'data attribute "' + attr + '" must start with "data-"');
}
}
});
return params;
}
}
/**
* @class Carousel object providing :
* - focus management
* - click and key events
* - ARIA attributes toggle
* - CSS classes toggle
*/
class A11yCarousel {
/**
* @desc Creates an instance of carousel
* @constructor
* @param {object} params
* @param {object} element
*/
constructor(params, element) {
this.errorMessage = A11yCarousel.name + ' : ';
/** @var {object} The params already checked */
this.params = params;
/** @var {HTMLElement[]} List of items in the carousel */
this.items = Array.from(element.querySelectorAll('[' + this.params.carouselListItem + ']'));
/** @var {HTMLElement[]} List of sub items in the carousel */
this.subItems = Array.from(element.querySelectorAll('[' + this.params.carouselSubListItem + ']'));
/** @var {HTMLElement} The current carousel */
this.carousel = this.checkCarousel(element);
/** @var {string} The current carousel id */
this.id = this.carousel.id;
/** @var {integer} The index of the current item */
this.currentIndex = 0;
/** @var {integer} The frame index of the current items */
this.currentFrame = 0;
/** @var {HTMLElement} The carousel items container */
this.carouselList = this.getCarousel(this.params.carouselList);
/** @var {HTMLElement} The carousel sub-items container */
this.carouselSubList = this.getCarousel(this.params.carouselSubList);
/** @var {HTMLElement} The carousel items inner container */
this.carouselListInner = this.getCarousel(this.params.carouselListInner);
/** @var {HTMLElement} The carousel sub-items inner container */
this.carouselSubListInner = this.getCarousel(this.params.carouselSubListInner);
/** @var {bool} Whether carousel contains bullets/tabs or not */
this.displayTabs = false;
/** @var {bool} Whether focus in on bullets/tabs */
this.hasTablistFocus = false;
/** @var {HTMLElement} Bullets/tabs container */
this.tablist = this.getCarousel(this.params.controlsBullets);
/** @var {HTMLElement[]} List of bullets/tabs items*/
this.tabs = this.getCarouselAll(this.params.controlsBullet);
/** @var {bool} Whether carousel contains arrows prev/next or not */
this.displayArrows = false;
/** @var {HTMLElement} Arrows prev/next container */
this.arrows = this.getCarouselAll(this.params.controlsArrows);
/** @var {HTMLElement} Previous button */
this.prevs = this.getCarouselAll(this.params.controlsArrowPrev);
/** @var {HTMLElement} Next button */
this.nexts = this.getCarouselAll(this.params.controlsArrowNext);
/** @var {bool} Whether carousel contains play/pause buttons or not */
this.displayPlayer = false;
/** @var {HTMLElement} Player */
this.player = this.getCarousel(this.params.controlsPlayer);
/** @var {HTMLElement} Play button */
this.play = this.getCarousel(this.params.controlsPlay);
/** @var {HTMLElement} Pause button */
this.pause = this.getCarousel(this.params.controlsPause);
/** @var {boolean} If carousel autoplays */
this.autoplay = this.carousel.getAttribute(this.params.settingsAutoplay) === 'true' ? true : false;
/** @var {boolean} If carousel is playing */
this.isPlaying = this.autoplay;
/** @var {boolean} If user has clicked play/pause button */
this.hasUserPlayOrPause = false;
/** @var {number} Animation interval */
this.animationInterval = null;
/** @var {integer} Animation duration */
this.animationDuration = this.getAnimationDuration();
/** @var {string} Animation type: none, translate, fade */
this.animationType = this.getAnimationType();
/** @var {integer} Number of slides per frame */
this.slidesPerFrame = this.getSlidesPerFrame();
/** @var {integer} The number of visible frames */
this.visibleFrames = this.getVisibleFrames();
/** @var {integer} The last frame index of the current items */
this.lastFrame = this.getLastFrame();
/** @var {integer} Slide margin for translation */
this.slideMargin = this.getSlideMargin();
/** @var {integer} Slide margin for sub-liste translation */
this.slideSubListMargin = this.getSlideMarginSubListe();
/** @var {HTMLElement} Live region containing slides */
this.liveRegion = this.getCarousel(this.params.carouselList);
// if (this.liveRegion !== null) {
// this.liveRegion.setAttribute('aria-live', 'off');
// }
/** @var {integer} First position on touch start */
this.firstX = 0;
/** @var {integer} Last position on touch move */
this.lastX = 0;
if (this.items.length < 2) {
return;
}
this.checkTabs();
this.checkArrows();
this.checkPlayer();
this.initItems();
window.addEventListener('resize', this.updateOnResize.bind(this));
window.dispatchEvent(new Event('resize'));
this.items.map((item) => {
item.addEventListener('focusin', this.handleItemFocusIn.bind(this));
item.addEventListener('focusout', this.handleItemFocusOut.bind(this));
item.addEventListener('touchstart', this.handleItemTouchStart.bind(this));
item.addEventListener('touchmove', this.handleItemTouchMove.bind(this));
item.addEventListener('touchend', this.handleItemTouchEnd.bind(this));
});
if (this.displayTabs) {
this.tablist.addEventListener('focusin', this.handleTablistFocusIn.bind(this));
this.tablist.addEventListener('focusout', this.handleTablistFocusOut.bind(this));
this.tabs.map((tab) => {
tab.addEventListener('click', this.handleTabClick.bind(this, tab));
tab.addEventListener('keydown', this.handleTabKeydown.bind(this));
});
}
if (this.displayArrows) {
[...this.prevs, ...this.nexts].map((arrow) => {
arrow.addEventListener('click', this.handleArrowClick.bind(this, arrow));
arrow.addEventListener('focusin', this.handleControlFocusIn.bind(this));
arrow.addEventListener('focusout', this.handleControlFocusOut.bind(this));
});
}
if (this.displayPlayer) {
this.play.addEventListener('click', this.handlePlay.bind(this));
this.pause.addEventListener('click', this.handlePause.bind(this));
this.carousel.addEventListener('mouseover', this.handleCarouselMouseover.bind(this));
this.carousel.addEventListener('mouseout', this.handleCarouselMouseout.bind(this));
[this.play, this.pause].map((button) => {
button.addEventListener('focusin', this.handleControlFocusIn.bind(this));
button.addEventListener('focusout', this.handleControlFocusOut.bind(this));
});
this.initPlayer();
}
}
/**
* @desc Check carousel and carousel items
*/
checkCarousel(carousel) {
if (!carousel.getAttribute('role') === 'region') {
throw new Error(this.errorMessage + 'carousel missing role="region"');
}
if (!A11yHelpers.hasAriaLabel(carousel) && !A11yHelpers.hasAriaLabelledBy(carousel)) {
throw new Error(this.errorMessage + 'carousel missing aria-label=""');
}
this.items.map((item) => {
if (!A11yHelpers.hasAriaLabel(item)) {
throw new Error(this.errorMessage + 'carousel item missing aria-label=""');
}
if (!A11yHelpers.hasAriaRoledescription(item)) {
throw new Error(this.errorMessage + 'carousel item missing aria-roledescription=""');
}
});
return carousel;
}
/**
* @desc Check tabs params
*/
checkTabs() {
if (this.tablist === null) {
return;
}
if (this.tablist.getAttribute('role') !== 'tablist') {
throw new Error(this.errorMessage + 'carousel bullets/tabs container missing role="tablist"');
}
if (!A11yHelpers.hasAriaLabel(this.tablist)) {
throw new Error(this.errorMessage + 'carousel bullets/tabs container missing aria-label=""');
}
this.tabs.map((tab) => {
if (tab.getAttribute('role') !== 'tab') {
throw new Error(this.errorMessage + 'tab missing role="tab"');
}
if (!A11yHelpers.hasAccessibleName(tab)) {
throw new Error(this.errorMessage + 'tab must have an accessible name');
}
if (tab.getAttribute('aria-controls') === undefined && tab.getAttribute('aria-controls') === '') {
throw new Error(this.errorMessage + 'tab must have aria-controls={listId}');
}
if (tab.getAttribute('aria-selected') === undefined && !['true', 'false'].contains(tab.getAttribute('aria-controls'))) {
throw new Error(this.errorMessage + 'tab must have aria-selected={true/false}');
}
});
if (this.items.length !== this.tabs.length) {
throw new Error(this.errorMessage + 'missing bullet/tab or carousel item');
}
if (this.items.length === this.tabs.length) {
this.displayTabs = true;
}
}
/**
* @desc Check arrows params
*/
checkArrows() {
[...this.prevs, ...this.nexts].map((arrow) => {
if (arrow === undefined || arrow === null) {
return;
}
if (!A11yHelpers.hasAccessibleName(arrow)) {
throw new Error(this.errorMessage + 'arrow must have an accessible name');
}
if (arrow.getAttribute('aria-controls') === undefined && arrow.getAttribute('aria-controls') === '') {
throw new Error(this.errorMessage + 'arrow must have aria-controls={listId}');
}
this.displayArrows = true;
});
}
/**
* @desc Check player params
*/
checkPlayer() {
[this.play, this.pause].map((button) => {
if (button === null) {
return;
}
if (!A11yHelpers.hasAccessibleName(button)) {
throw new Error(this.errorMessage + 'player button must have an accessible name');
}
if (button.getAttribute('aria-controls') === undefined && button.getAttribute('aria-controls') === '') {
throw new Error(this.errorMessage + 'player button must have aria-controls={listId}');
}
});
if (this.play !== null && this.pause !== null) {
this.displayPlayer = true;
}
}
/**
* @desc Get carousel element by data attribute
* @param {string} dataAttribute
* @return {HTMLElement}
*/
getCarousel(dataAttribute) {
return this.carousel.querySelector('[' + dataAttribute + ']');
}
/**
* @desc Get carousel list of elements by data attribute
* @param {string} dataAttribute
* @return {HTMLElement[]}
*/
getCarouselAll(dataAttribute) {
return Array.from(this.carousel.querySelectorAll('[' + dataAttribute + ']'));
}
/**
* @desc Get animation duration
* @return {integer}
*/
getAnimationDuration() {
let animationDuration;
animationDuration = getComputedStyle(this.carousel).getPropertyValue('--animation-duration');
animationDuration = animationDuration !== '' ? parseInt(animationDuration) : 3000;
return animationDuration;
}
/**
* @desc Get animation type
* @return {string}
*/
getAnimationType() {
let animationType;
animationType = getComputedStyle(this.carousel).getPropertyValue('--animation-type').replaceAll(' ', '').replaceAll('"', '');
animationType = ['translate', 'fade', 'none'].includes(animationType) ? animationType : 'none';
return animationType;
}
/**
* @desc Get number of slides per frame
* @return {integer}
*/
getSlidesPerFrame() {
let slidesPerFrame;
slidesPerFrame = getComputedStyle(this.carousel).getPropertyValue('--slides-per-frame');
slidesPerFrame = slidesPerFrame !== '' ? parseInt(slidesPerFrame) : 1;
return slidesPerFrame;
}
/**
* @desc Get number of visible frames
* @return {integer}
*/
getVisibleFrames() {
let visibleFrames;
const listWidth = parseInt(getComputedStyle(this.carouselListInner).getPropertyValue('width')) + this.slideMargin;
const itemWidth = parseInt(getComputedStyle(this.items[0]).getPropertyValue('width')) + this.slideMargin;
visibleFrames = Math.floor(listWidth / itemWidth);
return visibleFrames;
}
/**
* @desc Get calculated left + right margin for the element
* @param {HTMLElement} element
* @return {float}
*/
getMarginOf(element) {
let margin = 0;
let marginLeft = getComputedStyle(element).getPropertyValue('margin-left');
let marginRight = getComputedStyle(element).getPropertyValue('margin-right');
margin = parseFloat(marginLeft) + parseFloat(marginRight);
return margin;
}
/**
* @desc Get slide margin
* @return {float}
*/
getSlideMargin() {
let margin = 0;
if (this.items.length > 1) {
const item = this.items[1];
margin+= this.getMarginOf(item);
if (!this.items.includes(item.parentNode)) {
margin+= this.getMarginOf(item.parentNode);
}
}
return margin;
}
/**
* @desc Get sub-list slide margin
* @return {float}
*/
getSlideMarginSubListe() {
let margin = 0;
if (this.subItems.length > 1) {
const item = this.subItems[1];
margin+= this.getMarginOf(item);
if (!this.items.includes(item.parentNode)) {
margin+= this.getMarginOf(item.parentNode);
}
}
return margin;
}
/**
* @desc Get last frame index
* @return {integer}
*/
getLastFrame() {
return Math.ceil(this.items.length / this.slidesPerFrame) - 1;
}
/**
* @desc Initialize items attributes
*/
initItems() {
this.items.map((item, i) => {
// Visibility depending on visible frames
if (i < this.visibleFrames) {
item.setAttribute('aria-hidden', false);
item.classList.add(this.params.settingsActiveClass);
if (A11yHelpers.getFocusableNodes().includes(item.nodeName.toLowerCase())) {
item.removeAttribute('tabindex');
} else {
A11yHelpers.listFocusableElements(item).map((el) => {
el.removeAttribute('tabindex');
el.setAttribute('aria-hidden', false);
});
}
} else {
item.setAttribute('aria-hidden', true);
item.classList.remove(this.params.settingsActiveClass);
if (A11yHelpers.getFocusableNodes().includes(item.nodeName.toLowerCase())) {
item.setAttribute('tabindex', '-1');
} else {
A11yHelpers.listFocusableElements(item).map((el) => {
el.setAttribute('tabindex', '-1');
el.setAttribute('aria-hidden', true);
});
}
}
// Role depending on tabs
if (item.nodeName !== 'A') {
if (this.displayTabs) {
item.setAttribute('role', 'tabpanel');
}
// else {
// item.setAttribute('role', 'group');
// }
}
});
}
/**
* @desc Initialize player buttons and animation
*/
initPlayer() {
this.play.hidden = false;
this.pause.hidden = true;
if (this.isPlaying) {
this.play.hidden = true;
this.pause.hidden = false;
this.playNextSlide();
}
}
/**
* @desc On window resize, get new number of slides per frame
*/
updateOnResize() {
this.slidesPerFrame = this.getSlidesPerFrame();
this.visibleFrames = this.getVisibleFrames();
this.slideMargin = this.getSlideMargin();
this.slideSubListMargin = this.getSlideMarginSubListe();
this.lastFrame = this.getLastFrame();
this.initItems();
this.moveToSlide(0);
}
/**
* @desc Store touch position on start
* @param {TouchEvent} e
*/
handleItemTouchStart(e) {
this.firstX = e.changedTouches[0].pageX;
}
/**
* @desc Store touch position on move
* @param {TouchEvent} e
*/
handleItemTouchMove(e) {
this.lastX = e.changedTouches[0].pageX;
}
/**
* @desc Trigger event on touch end, only on a meaningful movement
* @param {TouchEvent} e
*/
handleItemTouchEnd(e) {
if (Math.abs(this.firstX - this.lastX) < document.body.clientWidth / 5) {
return;
}
if (this.lastX > this.firstX) {
this.movePrevious();
} else {
this.moveNext();
}
}
/**
* @desc Deal with events on tab focus in
* @param {FocusEvent} e
*/
handleTablistFocusIn(e) {
this.hasTablistFocus = true;
this.updateLive(true);
}
/**
* @desc Deal with events on tab focus out
* @param {FocusEvent} e
*/
handleTablistFocusOut(e) {
this.hasTablistFocus = false;
this.updateLive(false);
}
/**
* @desc Deal with events on tab click
* @param {PointerEvent} e
*/
handleTabClick(tab, e) {
const newIndex = parseInt(tab.getAttribute(this.params.controlsBullet));
this.moveToSlide(newIndex);
}
/**
* @desc Deal with events on tab keydown
* @param {KeyboardEvent} e
*/
handleTabKeydown(e) {
switch (e.key) {
case A11yHelpers.key().LEFT:
this.movePrevious();
break;
case A11yHelpers.key().RIGHT:
this.moveNext();
break;
case A11yHelpers.key().HOME:
this.moveToSlide(0);
break;
case A11yHelpers.key().END:
this.moveToSlide(this.items.length - 1);
break;
default:
break;
}
if (this.isPlaying) {
this.triggerPause();
}
}
/**
* @desc Deal with events on item focus in
* @param {FocusEvent} e
*/
handleItemFocusIn(e) {
if (this.isPlaying) {
this.triggerPause();
}
}
/**
* @desc Deal with events on item focus out
* @param {FocusEvent} e
*/
handleItemFocusOut(e) {
if (this.autoplay && !this.isPlaying && !this.hasUserPlayOrPause) {
this.triggerPlay();
}
}
/**
* @desc Deal with events on arrow click
* @param {HTMLElement} arrow The arrow button element
* @param {PointerEvent} e
*/
handleArrowClick(arrow, e) {
if (arrow.getAttribute(this.params.controlsArrowPrev) !== null) {
this.movePrevious();
} else {
this.moveNext();
}
}
/**
* @desc Deal with events on control button focus in
* @param {FocusEvent} e
*/
handleControlFocusIn(e) {
this.updateLive(true);
}
/**
* @desc Deal with events on control button focus out
* @param {FocusEvent} e
*/
handleControlFocusOut(e) {
this.updateLive(false);
}
/**
* @desc Deal with events on carousel mouse over
* @param {MouseEvent} e
*/
handleCarouselMouseover(e) {
if (e.target === this.play || e.target === this.pause) {
return;
}
if (this.isPlaying) {
this.triggerPause();
}
this.updateLive(true);
}
/**
* @desc Deal with events on carousel mouse out
* @param {MouseEvent} e
*/
handleCarouselMouseout(e) {
if (e.target === this.play || e.target === this.pause) {
return;
}
if (this.autoplay && !this.hasUserPlayOrPause) {
this.triggerPlay();
}
this.updateLive(false);
}
/**
* @desc Deal with play button
* @param {PointerEvent} e
*/
handlePlay(e) {
this.hasUserPlayOrPause = true;
this.triggerPlay();
this.pause.focus();
}
/**
* @desc Deal with pause button
* @param {PointerEvent} e
*/
handlePause(e) {
this.hasUserPlayOrPause = true;
this.triggerPause();
this.play.focus();
}
/**
* @desc Update params and play next
*/
triggerPlay() {
this.isPlaying = true;
this.play.hidden = true;
this.pause.hidden = false;
this.playNextSlide();
}
/**
* @desc Update params and clear timeout
*/
triggerPause() {
this.isPlaying = false;
this.play.hidden = false;
this.pause.hidden = true;
clearTimeout(this.animationInterval);
}
/**
* @desc Update live region
*/
updateLive(isLive) {
if (isLive) {
this.liveRegion.ariaLive = 'polite';
} else {
this.liveRegion.ariaLive = 'off';
}
}
/**
* @desc Move to next slide or first
*/
moveNext() {
let nextIndex = this.currentIndex + this.slidesPerFrame;
if (nextIndex >= this.items.length) {
nextIndex = 0;
}
this.moveToSlide(nextIndex);
}
/**
* @desc Move to previous slide or last
*/
movePrevious() {
let previousIndex = this.currentIndex - this.slidesPerFrame;
if (previousIndex < 0) {
previousIndex = this.lastFrame * this.slidesPerFrame;
}
this.moveToSlide(previousIndex);
}
/**
* @desc Move to slide by index
* @param {integer} index
*/
moveToSlide(index) {
if (index === null || index === undefined) {
return;
}
if (index === this.currentIndex) {
return;
}
if (index === 0) {
this.currentFrame = 0;
} else if (index === this.items.length - 1) {
this.currentFrame = this.lastFrame;
} else {
if (index >= this.currentFrame * this.slidesPerFrame) {
this.currentFrame++;
} else {
this.currentFrame--;
}
}
this.currentIndex = index;
this.items.map((item, i) => {
let show = false;
if (i === this.currentIndex) {
show = true;
}
if (this.animationType === 'translate') {
if (i > this.currentIndex && i - this.currentIndex < this.visibleFrames ) {
show = true;
}
}
if (show) {
item.setAttribute('aria-hidden', false);
item.classList.add(this.params.settingsActiveClass);
item.removeAttribute('tabindex');
} else {
item.setAttribute('aria-hidden', true);
item.classList.remove(this.params.settingsActiveClass);
item.tabIndex = -1;
}
});
this.subItems.map((item, i) => {
let show = false;
if (i === this.currentIndex) {
show = true;
}
if (this.animationType === 'translate') {
if (i > this.currentIndex && i - this.currentIndex < this.slidesPerFrame ) {
show = true;
}
}
if (show) {
item.setAttribute('aria-hidden', false);
item.classList.add(this.params.settingsActiveClass);
item.removeAttribute('tabindex');
} else {
item.setAttribute('aria-hidden', true);
item.classList.remove(this.params.settingsActiveClass);
item.tabIndex = -1;
}
});
if (this.displayTabs) {
this.tabs.map((tab, i) => {
if (i === this.currentIndex) {
tab.ariaSelected = true;
tab.tabIndex = 0;
tab.classList.add(this.params.settingsActiveClass);
if (this.hasTablistFocus) {
tab.focus();
}
} else {
tab.ariaSelected = false;
tab.tabIndex = -1;
tab.classList.remove(this.params.settingsActiveClass);
}
});
}
const indexDisplay = this.getCarouselAll(this.params.carouselIndex);
if (indexDisplay.length) {
indexDisplay.map((index) => {
index.innerText = this.currentIndex + 1;
});
}
this.animateTranslation();
if (this.subItems.length > 0){
this.animateSubTranslation();
}
if (this.isPlaying) {
clearTimeout(this.animationInterval);
this.playNextSlide();
}
}
/**
* @desc Play next slide
*/
playNextSlide() {
this.animationInterval = setTimeout(() => {
this.moveNext();
this.animateTranslation();
if (this.subItems.length > 0) {
this.animateSubTranslation();
}
}, this.animationDuration);
}
/**
* @desc Update CSS translation value
*/
animateTranslation() {
if (this.carouselListInner === null || this.animationType !== 'translate') {
return;
}
const slideWidth = parseInt(getComputedStyle(this.items[0]).getPropertyValue('width'));
const translate = slideWidth * this.currentIndex + this.slideMargin * this.currentIndex;
this.carouselListInner.style.transform = 'translateX(-' + translate + 'px)';
}
/**
* @desc Update CSS translation value for sub items
*/
animateSubTranslation() {
if (this.carouselSubListInner === null || this.animationType !== 'translate') {
return;
}
const slideWidth = parseInt(getComputedStyle(this.subItems[0]).getPropertyValue('width'));
const translate = slideWidth * this.currentIndex + this.slideSubListMargin * this.currentIndex;
$(window).on('resize', () => {
if (!matchMedia("screen and (min-width: 1024px)").matches) {
this.carouselSubListInner.style.transform = 'translateX(-' + (translate) + 'px)';
} else {
if (translate !== 0)
{
this.carouselSubListInner.style.transform = 'translateX(-' + (translate - slideWidth) + 'px)';
} else {
this.carouselSubListInner.style.transform = '';
}
}
}).trigger('resize');
}
}
const carousels = new A11yCarousels();
if (carousels) {
const updateCarouselClasses = (carousel, e) => {
const $carouselList = $('#' + carousel.carouselList.id);
$carouselList.removeClass('first-frame');
$carouselList.removeClass('last-frame');
if (carousel.currentFrame === 0) {
$carouselList.addClass('first-frame');
}
if (carousel.currentFrame === carousel.lastFrame) {
$carouselList.addClass('last-frame');
}
if (carousel.items.length <= carousel.getSlidesPerFrame()) {
$(carousel.carousel).find('.slider-nav, .slider-nav-numbers').css('display', 'none');
} else {
$(carousel.carousel).find('.slider-nav, .slider-nav-numbers').css('display', '');
}
if (e.currentTarget !== undefined) {
if ($(e.currentTarget).hasClass('slider-nav__arrow')) {
$(carousel.carousel).find('.slider-nav__arrow').removeClass('fade');
}
if ($(e.currentTarget).hasClass('slider-nav-mobile__arrow')) {
$(carousel.carousel).find('.slider-nav-mobile__arrow').removeClass('fade');
}
}
};
$(document).ready((e) => {
carousels.list.forEach((carousel) => updateCarouselClasses(carousel, e));
});
$(window).on('resize', (e) => {
carousels.list.forEach((carousel) => updateCarouselClasses(carousel, e));
});
carousels.list.forEach((carousel) => {
$('#' + carousel.carouselList.id).on('touchend', (e) => {
updateCarouselClasses(carousel, e);
});
$(carousel.carousel).find('button').each((i, button) => {
$(button).on('click', (e) => updateCarouselClasses(carousel, e));
});
});
}
Also see: Tab Triggers