Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enable slick only under a certain window width and disable it when window width turns bigger

I am writing a blog that shows posts with a slick carousel ONLY when the viewport is a certain value, so on mobile devices is it possible to scroll them.

I tried a lot of ways but none was successful. Various problems occurred.

The code snippet closest to my goal is the following:

function slickify(){
    $('.goslick').slick({
        dots: false,
        infinite: true,
        speed: 300,
        slidesToShow: 1,
        slidesToScroll: 1,
            responsive: [
                {
                    breakpoint: 500,
                     settings: "unslick"
                }
            ]
     });
                }
    slickify();

    $(window).resize(function(){
        var $windowWidth = $(window).width();
        if ($windowWidth > 500) {
            slickify();   
        }
    });

Unfortunately this does the opposite of my goal; it enables the carousel when the viewport is bigger than the value indicated by the relative variable. I really can't reverse this script.

Here is the not-working prototype

like image 991
Matteo Corona Avatar asked Nov 26 '25 22:11

Matteo Corona


1 Answers

I made it working with this snippet:

         function slickify(){
            $('.goslick').slick({
                autoplay: false,
                speed: 300,
                slidesToShow: 1,
                slidesToScroll: 1
            });
          }

          $(window).resize(function(){
              var $windowWidth = $(document).width();
              if ($windowWidth < 500) {
                  slickify();   
              }else{
                  $('.goslick').slick("unslick");
              }
          });

Note that I removed the call of the slickify() function out of the window.resize and I replaced windows.width with document.width in order to prevent that the slick loads bad going back to the page or starting it for the first time.

like image 128
Matteo Corona Avatar answered Nov 29 '25 13:11

Matteo Corona



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!