javascriptjqueryaccessibilityswiper.jspause

Pausing SwiperJS autoplay when slider entered by keyboard tab, no mouse


I'm working an accessibility request and am trying to pause the slideshow when a user enters the slider by tabbing into it. It's already configured to pause on mouse hover and resume on mouse out, but it still slides when tabbed into any of the elements within the slider.

I checked the API for SwiperJS and saw there's this:

swiper.autoplay.pause()

But how can I tell when the slider is the focus when a user navigates the website by keyboard and tabs into it?

I tried these jQuery snippets in the browser console, but they're not pausing the slideshow:

$(window).keyup(function (e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 9 && $('.carousel-wrapper:focus-within').length) {
        swiper.autoplay.pause();
    }
});

$(window).keyup(function (e) {
    var code = (e.keyCode ? e.keyCode : e.which);
    if (code == 9 && $('.carousel-wrapper:focus-within').length) {
        swiper.autoplay = false;
    }
});

Solution

  • You should use the focusin event to pause autoplay.

    There are different ways to focus an element, especially with assistive technology there might be no keyboard involved. It’s a dangerous assumption, to listen to keyboard events. Voice control software, for example, allows focusing elements simply by saying “Click next button”, which will also focus it.

    Since it’s quite useless and unreliable to figure out which elements exactly can receive focus, you need an event that bubbles up to the slider element, which focusin does.

    You’ll need to use the variable you used to store the reference to the Swiper instance when you initialised it.

    const swiper = new Swiper(…);
    …
    swiper.el.addEventListener("focusin", () => swiper.autoplay.pause());
    

    The Carousel pattern of the ARIA Authoring Practices Guide (APG) also mentions the following concerning autoplay:

    If the carousel can automatically rotate, it also:

    • Has a button for stopping and restarting rotation. This is particularly important for supporting assistive technologies operating in a mode that does not move either keyboard focus or the mouse.
    • Stops rotating when keyboard focus enters the carousel. It does not restart unless the user explicitly requests it to do so.
    • Stops rotating whenever the mouse is hovering over the carousel.