Search code examples
javascripthtmljquerycustom-data-attributeswiper.js

Get text from data attribute on 'active' slide and update paragraph element with its value


I've tried (and failed) to write some JavaScript that gets the data-attribute from the 'active' slide of a carousel, then adds the same text into a p element outside the container. When the carousel gets a new 'active' slide, the text should change - fading slightly if possible.

I don't want the caption to appear within the carousel and overflow: hidden prevents me from adding a caption within the slide and then positioning it outside with absolute.

If easier, I could get the text from a p within the slide rather data-. Then just hide the text within.

This was my attempt:

var caption = document.querySelector(".caption");

if(document.querySelector(".swiper-slide").classList.contains("swiper-slide-active")){
    console.log(this.getAttribute('data-caption'));
    caption.innerHTML('data-caption');
}

I found a CodePen using the same carousel so I thought I'd add a basic example to check what happens when the class is added/removed from the active slides.

CodePen: https://codepen.io/moy/pen/OJOyGKR

Where am I going wrong? Keen to understand JS a bit more!


Solution

  • Swiper JS, Events Docs has useful Event methods like init, slideChange etc, which are part of the options on Object.

    Such event callback functions are made in order trigger a desired function once the Swiper performs an internal change. It's a way to say: "When you do this, let me also do that"

    Here's how your JS should look:

    const EL_caption = document.querySelector(".caption");
    
    function doSomethingWithActiveSlide() {
        const EL_currentSlide = this.slides[this.activeIndex - 1];    
        EL_caption.innerHTML = EL_currentSlide.dataset.caption;
    }
    
    const MySwiper = new Swiper('.swiper-container', {
        loop: true,
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
        pagination: {
            el: '.swiper-pagination',
        },
        // Events
        on: {
            init: doSomethingWithActiveSlide,
            slideChange: doSomethingWithActiveSlide,
        }
    });