frafor frafor - 29 days ago 24
Javascript Question

BxSlider destroySlider() function not working: slider undefined or is not a function

I have a bunch of posts displayed in a carousel using bxslider. The code that fires the carousel looks like:

jQuery(document).ready(function() {

var carouselWidth = 640;
var carousel;
var carousel_Config = {
minSlides: 1,
maxSlides: 5,
slideWidth: 285,
slideMargin: 25,
controls: false,
pagerSelector: '.pager'
}

if( jQuery(window).width() > carouselWidth) {
carousel = jQuery('.event-carousel').bxSlider(carousel_Config);
};

jQuery(window).resize(function() {
if( jQuery(window).width() > carouselWidth) {
carousel = jQuery('.event-carousel').bxSlider(ttCarousel_Config);
} else {
carousel.destroySlider();
}
});

});


Easy, right?

Problem is that destroySlider() does not work: I get that "carousel" is undefined. It's the same if I try with:

jQuery('.event-carousel').bxSlider().destroySlider();


I tried to declare "carousel" outside the jQuery(document...) putting var carousel; at top of the script but I always get the same result in console: Carousel is undefined.

How can I solve this problem?

Answer

Could you please try with below code:

jQuery(document).ready(function() {

var carouselWidth = 640;
var carousel = null;
var carousel_Config = {
          minSlides: 1,
          maxSlides: 5,
          slideWidth: 285,
          slideMargin: 25,
          controls: false,
          pagerSelector: '.pager'
}

    if( jQuery(window).width() > carouselWidth) {
        if(carousel == null)
            carousel = jQuery('.event-carousel').bxSlider(carousel_Config);
    };

    jQuery(window).resize(function() {
        if( jQuery(window).width() > carouselWidth) {
            if(carousel == null)
                carousel = jQuery('.event-carousel').bxSlider(ttCarousel_Config);
        } else {
            if(carousel){
                carousel.destroySlider();
                carousel = null;
            }
        }
    });

});

Please check carousel object before destroying it. Same applies for initializing the carousel. If its already there then no need to create/re-init the carousel.

Comments