Search code examples
jquerybxslider

bxSlider, destroy the slider if screen is wider than X


I'm trying to use jQuery bxSlider only when the screen is small, for mobile devices. So I'm calling this function and the first part of the if/else statement works, but not the second "else" where I try to destroy the slider:

$(window).on("resize", function (e) {
        checkScreenSize();
    });

    checkScreenSize();

    function checkScreenSize(){

        var slider = $(".thumbnails-custom-list").bxSlider();

        var newWindowWidth = $(window).width();
        if (newWindowWidth < 481) {

            $(".thumbnails-custom-list").bxSlider();

        } else {
             $(".thumbnails-custom-list").bxSlider().destroySlider();
        }

    }

I get a console error:

".destroySlider is not a function"


Solution

  • Store the slider in a variable which is declared globally and then destroy bxSlider on that variable.

    $(window).on("resize", function (e) {
            checkScreenSize();
        });
    
        checkScreenSize();
    
        function checkScreenSize(){
    
            slider = $(".thumbnails-custom-list").bxSlider({    minSlides: 1,
    maxSlides: 8,
    slideWidth: 189,
    slideMargin: 0,
    ticker: true,
    speed: 50000});
    
            var newWindowWidth = $(window).width();
            if (newWindowWidth >= 481) {
                // destroy slider
                slider.destroySlider();
            }
    
        }
        
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bxslider/4.2.12/jquery.bxslider.min.js"></script>
    <ul class="thumbnails-custom-list">
      <li><img src="http://placehold.it/160x189&text=1" /></li>
      <li><img src="http://placehold.it/160x189&text=2" /></li>
      <li><img src="http://placehold.it/160x189&text=3" /></li>
      <li><img src="http://placehold.it/160x189&text=4" /></li>
      <li><img src="http://placehold.it/160x189&text=5" /></li>
      <li><img src="http://placehold.it/160x189&text=6" /></li>
      <li><img src="http://placehold.it/160x189&text=7" /></li>
      <li><img src="http://placehold.it/160x189&text=8" /></li>
    </ul>