Ronak
Ronak

Reputation: 51

Getting the text of the current slide in FlexSlider

I am using FlexSlider on my website. I want to get the text of the current slide. I try to do it in the after function:

$(window).load(function() {
    $('.flexslider').flexslider({
        startAt: 1,
        controlNav: false,
        animationLoop: false,
        slideshow: false,
        animation: "slide",
        directionNav: true,
        after: function(){
            var curSlide = $('#slider').data('flexslider').currentSlide;
            alert("current slide="+curSlide.text());
        }   
    });
}); 

I tried using the text() function but it's not working. How can I do this?

Upvotes: 1

Views: 5353

Answers (1)

currentSlide returns the number of the current slide, not the element. You can use nth-of-type to find the element.

$(window).load(function() {
    $('.flexslider').flexslider({
        startAt: 1,
        controlNav: false,
        animationLoop: false,
        slideshow: false,
        animation: "slide",
        directionNav: true,
        after: function(slider){
            var curSlide = slider.find("li:nth-of-type("+(slider.currentSlide+1)+")")[0];
            var text = $(curSlide).text().trim();
            alert(text);
        }   
    });
}); 

Here is a working JSFiddle

Explanation:

  1. According to the flexslider documentation, each method has a reference to the slider object.
  2. Testing around I realized that slider.currentSlide returns the number of the current slide, starting from 0.
  3. We use the slider object and find to get the current slide element. We need to add 1 to slider.currentSlide because it starts from 0, and the nth-of-type selector starts with one.
  4. I realized that the find method returned 3 li elements but only the first one was the one needed, that was why I selected the [0] element.
  5. Finally I use trim() to remove the extra white spaces.

UPDATE

I realized that there was a better way to do it. FlexSlider assigns the class flex-active-slide to the active slide, so it is easier to get the slide element.

$(window).load(function() {
    $('.flexslider').flexslider({
        startAt: 1,
        controlNav: false,
        animationLoop: false,
        slideshow: false,
        animation: "slide",
        directionNav: true,
        after: function(slider){
            var curSlide = slider.find("li.flex-active-slide");
            var text = $(curSlide).text().trim();
            alert(text);
        }   
    });
}); 

Upvotes: 2

Related Questions