Why Flexsider’s Carousel Demo with Dynamic Sizing Doesn’t Work

I’ve scratched my head a few too many times to not post this (if only for my own reference). The ever amazing and rarely updated Flexslider from the folks at Woocommerce has a bug in one of the demos that doesn’t make it operate as intended. It’s the carousel with a dynamic number of elements that changes with the width of the site. You can find it here.

There are two problems with their source code.

Firstly despite declaring a ‘flexslider’ variable at the top of the page they don’t initialize the slider into this. You need to do this to update the sliders min and max values.

Secondly it seems they’re incorrectly updating the min and max sizes on the event of the window resizing. They’re using the property below which doesn’t  work (especially because they’ve not associated their ‘flexslider’ variable with the slider itself).

flexslider.vars.minItems = gridSize;
flexslider.vars.maxItems = gridSize;

However to correctly update this value in Flexslider you need to do the folllowing. Please note the different with $flexslider and flexslider is just my naming convention.

$flexslider.data('flexslider').vars.minItems = gridSize;
$flexslider.data('flexslider').vars.maxItems = gridSize;

Heres the fully working code.

var $window = $(window),
    $flexslider;
 
// tiny helper function to add breakpoints
function getGridSize() {
  return (window.innerWidth < 768) ? 1 : 3;
}
 
$window.load(function() {
  // Carousel Homepage
  $flexslider = $('.flexslider').flexslider({
    animation: "slide",
    itemWidth: 360,
    itemMargin: 25,
    minItems: getGridSize(),
    maxItems: getGridSize(),
    slideshow: false,
    prevText: "Prev"
  });  
});
 
if(!!$('.flexslider').length) {
  // check grid size on resize event
  $window.resize(function() {
    var gridSize = getGridSize();
    $flexslider.data('flexslider').vars.minItems = gridSize;
    $flexslider.data('flexslider').vars.maxItems = gridSize;
  });
}

Should you need to add additional break points or different breakpoints just update the getGridSize function.