Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 776
byronyasgur Avatar asked Jun 26 '12 20:06

byronyasgur


2 Answers

You can avoid global variables by accessing the flexslider object with:

$(element).data('flexslider')

So in your case you'd use:

$(element).data('flexslider').currentSlide
like image 64
Lewis Avatar answered Nov 13 '22 18:11

Lewis


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.

like image 29
riku Avatar answered Nov 13 '22 19:11

riku