Search code examples
javascriptjqueryflexslider

How do I get the 'Flexslider' current image number into a variable which I can use in a function?


I am using flexslider. There is an example under the advanced tap on this page (in the section "The new, robust Callback API" where they use slider.currentSlide to get the number of the current slide.

How can I access this value in a completely different function? I am thinking of a global variable but I don't know if that will work and I don't know if it's possible to declare a variable within a function as global.


Solution

  • You can declare a global variable and set the value in the after callback function. Here's some pseudocode to help you get the idea:

    var curSlide;
    $(window).load(function() {
      $('.flexslider').flexslider({
        after: function(slider) {
          window.curSlide = slider.currentSlide;
        }
      });
    });
    
    function useCurSlideHere() {
      alert(window.curSlide);
    }
    

    Although ideally you'd avoid using a global variable and you could make the useCurSlideHere function into a class which you create an instance of on window.load and use it when you pass the curSlide variable in the after callback function.

    $(window).load(function() {
      var customSlider = new useCurSlideHere();
      $('.flexslider').flexslider({
        after: function(slider) {
          customSlider.setCurSlide(slider.currentSlide);
        }
      });      
    });
    
    function useCurSlideHere() {
      this.curSlide = 0;
    
      this.setCurSlide = function(curSlide) {
        this.curSlide = curSlide;
      }
    
      this.getCurSlide= function() {
        alert(this.curSlide);
      }
    }
    

    EDIT: Edited the answer to use slider.currentSlide.