Slick: Can't destroy slick - unslick function returns error

Created on 10 Jul 2014  ·  59Comments  ·  Source: kenwheeler/slick

I'm unable to destroy a slick instance. Calling $('.your-slider').unslick(); returns Uncaught TypeError: Cannot read property 'parent' of null on line 575 of slick.js. It would appear $slides is undefined. Is anyone else seeing this issue?

Most helpful comment

Not sure if anyone is still looking at this but I was stuck on it for an hour. I realised I have either read the way you call methods wrong or it's changed.

Instead of carousel.unslick(); you should use carousel.slick("unslick");

All 59 comments

Yes, we are. And yes, I've echoed _.$slides and it is null when this error occurs.

Same here.

Getting this as well.

I've echoed _.$slides and it is null when this error occurs.

Interesting. I suspect this is also why I can't access slide attributes in onAfterChange in https://github.com/kenwheeler/slick/issues/411.

Looking into this today

At what point are you trying to unslick this? $slides not being defined is the bigger problem. Is it working prior to unslicking?

For me, yes, it was working - I'd called slick() on a wrapper element,
checked the carousel was working (and had attached slickNext and slickPrev
to custom elements), then I try to unslick when a particular click event
happens, and I get this error.

On Saturday, 2 August 2014, Ken Wheeler [email protected] wrote:

At what point are you trying to unslick this? $slides not being defined is
the bigger problem. Is it working prior to unslicking?


Reply to this email directly or view it on GitHub
https://github.com/kenwheeler/slick/issues/369#issuecomment-50965063.

Can I see the actual unslick code?

Sure (I wrote it using Coffeescript):

init: ->
  @attachCarousel()
  @handleCarouselDestroy()

attachCarousel: ->
  $('.product__images').slick
    prevArrow: $('.images-navigation__ctas--prev')
    nextArrow: $('.images-navigation__ctas--next')

handleCarouselDestroy: ->
  $('.remove-carousel').click ->
    $('.product__images').unslick()

Same for me. I call slick() on an element on document ready, which works as expected. I have a function to destroy slick when an event fires, which throws the error.

var $thumbnailBar = $('.thumbnail-bar');

$thumbnailBar.slick({
  // slick options
});

function destroyThumbnailBarSlick() {
  $thumbnailBar.unslick();
}

can one of you guys make a fiddle? I can't reproduce this.

Embarrassingly I've traced my issue to something else. The unslick method was being fired on window.resize, as was an errant $(element).slick(). The slick method hadn't initialised before unslick was called, causing the issue. I can't speak for others of course, but my issue has been resolved. Apologies all.

Here's a js fiddle which shows that both the slickSetOption and unslick methods don't work:
http://jsfiddle.net/renak/bjxLjw3v/3/

@renak You're trying to unslick the button, not the slider. Also, modes like center or fade can't be set.

Oh oops. Typo on my end. Thanks for the info on the options setting. Do you have documentation somewhere on which options can be updated?

So what about this problem? I am trying to unslick at a specific width (responsive site, only use slick below 751px). I get the same problem.

function initSlick() {  
    var width = jQuery(window).width(); 
    if (width>751) {
        jQuery('.slickNews, div.facts').unslick();
    }
    if (width<751) {
        jQuery('.slickNews, div.facts').slick({
            dots: true,
            infinite: false,
            speed: 300,
            slidesToShow: 1,
            slidesToScroll: 1
        });
    }
}

Having this issue as well. unslick does not always work

In my case I needed to destroy slick at a certain window size. This worked for me:

var $carousel = $('.carousel');

if (breakpoint === 'mobile') {
  if($carousel.hasClass('slick-initialized')) {
    $carousel.unslick();
  }
  $carousel.slick();
} else {
  $carousel.unslick();
}

Similar to @simonkitson I was calling the slick/unslick function on each resize so the function attempting to recreate the slider prevented the sliders removal.

My addition to @wtran is as follows:

    var $carousel = $('.element_class');

    // console.log( $(window).width() + '>' + commonBreakpoint );

    if ( $(window).width()  >= commonBreakpoint) { 

        // console.log('unslick');

        if($carousel.hasClass('slick-initialized')) {
            $carousel.unslick();
        }

    } else {

        // console.log('slick');

        if(!$carousel.hasClass('slick-initialized')) {

            $carousel.slick({
                dots: true,
                arrows: false,
                infinite: false,
                speed: 100,
                slidesToShow: 1,
                slidesToScroll: 1
            });
        }

    }
           var $carousel = $('#wrapper-tab-mobile');
           function showSliderScreen($widthScreen) {
               console.log($widthScreen);

               if ($widthScreen <= "890") {
                   if (!$carousel.hasClass('slick-initialized')) {
                       $carousel.slick({
                           slidesToShow: 5,
                           slidesToScroll: 1,
                           infinite: false,
                           arrows: false,
                           focusOnSelect: true,responsive: [
                            {
                                breakpoint: 768,
                                settings: {
                                    centerPadding: '40px',
                                    slidesToShow: 3
                                }
                            },
                           {
                               breakpoint: 480,
                               settings: {
                                   slidesToShow: 2
                               }
                           }]
                       });
                   }

               } else {
                   if ($carousel.hasClass('slick-initialized')) {
                       $carousel.unslick();
                   }
                }   
           }

           var widthScreen = $(window).width();
           $(window).ready(showSliderScreen(widthScreen)).resize(
               function () {
                   var widthScreen = $(window).width();
                   showSliderScreen(widthScreen);
               }
           );

Using http://responsejs.com/ to detect breakpoints and i’m getting the same “Uncaught TypeError: Cannot read property 'parent' of null ” error.

Response.resize(function(){ if (Response.media("(max-width: 1025px)").matches) { $introslides.slick({ slide: '.slide', }) } if (Response.media("(min-width: 1026px)").matches) { console.log('unslick'); $introslides.unslick(); } });

@nathanaelphilip try using @flesch91's technique. check for the 'slick-initialized' class before calling unslick. The carousel is performing a kind of "init" on resizing and is temporarily unavailable. If you call unslick during that time, you get that error.

@dan-diaz works like a charm. Thanks @flesch91!

@nathanaelphilip , @dan-diaz ;) You're welcome! Not at all )

HI All, I too am having an issue when calling unslick, i get this error

TypeError: _.$slides is null if (_.$slides.parent().hasClass('slick-track'))

I have created a StackOverflow with a detailed account of the scenario here

Any assistance would be greatly appreciated

@richlewis14 why do you have 3 slick clones in a row? Can I see a jsfiddle?

Thanks @flesch91! Your answer works fine for me!

I followed these instructions but it's still not working. I keep getting the same error "Uncaught TypeError: Cannot read property 'parent' of null".

I'm trying to do the opposite and kill the slideshow on mobile. Please help :)

var carousel = $j('.fundraiser-list');

function showSliderScreen($screenWidth) {
    if($screenWidth >= "480") {
        if(!carousel.hasClass('slick-initalized')){
            carousel.slick({
                responsive: [
                    {
                        breakpoint: 2100,
                        settings: {
                            slidesToShow:5
                        }
                    },
                     {
                        breakpoint: 1550,
                        settings: {
                            slidesToShow: 4
                        }
                    },
                    {
                        breakpoint: 1250,
                        settings: {
                            slidesToShow: 3
                        }
                    },
                    {
                        breakpoint: 768,
                        settings: {
                            slidesToShow: 2
                        }
                    },
                    {
                        breakpoint: 480,
                        settings: {
                            slidesToShow: 1
                        }
                    }
                ]
            });
        }
    } else {
        console.log("smaller than 480");
        if (carousel.hasClass('slick-initialized')) {
            carousel.unslick();
        }
    }
}

var screenWidth = $j(window).width();
$j(window).ready(showSliderScreen(screenWidth)).resize(function(){
    var screenWidth = $j(window).width();
    showSliderScreen(screenWidth);
});

Not sure if anyone is still looking at this but I was stuck on it for an hour. I realised I have either read the way you call methods wrong or it's changed.

Instead of carousel.unslick(); you should use carousel.slick("unslick");

Yeah, calling methods was recently changed:
https://github.com/kenwheeler/slick/releases/tag/1.4.0

not working for me having this issue:
Uncaught TypeError: Cannot read property 'removeClass' of nullslick.min.js?ver=20140101:694 Slick.destroyslick.min.js?ver=20140101:2082
Slick.unslickslick.min.js?ver=20140101:2143
$.fn.slickcustom.js?ver=20140101:73
(anonymous function)jquery.js?ver=1.11.1:3
m.event.dispatchjquery.js?ver=1.11.1:3
m.event.add.r.handle


var aboutLogos = $('#about-logos-box');
$(window).resize(function(){
aboutColumns();
if(window.innerWidth <= 767){
aboutLogos.slick({
adaptiveHeight: true,
autoplay: true,
arrows: false,
dots: false,
autoplaySpeed: 7000
});
} else {
if(aboutLogos.hasClass('slick-initialized')) {
aboutLogos.slick('unslick');
}
}
});

Has no one been able to solve this issue? Does slick carousel not work properly with dynamically loaded content? Is using it advised? I have included it in my application and am desperately trying to find a solution or an alternative fast.

in slick.js file
append new method

Slick.prototype.fuckingDestroy = function() {

    var _ = this;

    _.destroy();

    _.hasDestroyed = true;
};  

modify method Slick.prototype.checkResponsive, prepend

Slick.prototype.checkResponsive = function(initial) {

    if( this.hasDestroyed )
    {
        return false;
    }

    ...
    ...
    ...
}

append to Slick.prototype.init method

Slick.prototype.init = function() {
    ...
    ...
    ...

    _.hasDestroyed = false;
}

for destroy slick, use

$(element).slick('fuckingDestroy');

I created function for easy using, set initialSize for every elements

slickPush(
[   
    {
        el: '.partner-list',
        settings: { dots: true, arrows: false, infinite: true, speed: 300, slidesToShow: 6, slidesToScroll: 6, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 4, slidesToScroll: 4, infinite: true, dots: true } }, { breakpoint: 768, settings: { slidesToShow: 3, slidesToScroll: 3 } } , { breakpoint: 550, settings: { slidesToShow: 2, slidesToScroll: 2 } } ] },
        initialSize: 0 // not depending on the size of the screen
    },

    {
        el: '.review-list',
        settings: { dots: false, arrows: false, infinite: true, centerMode: true, speed: 300, slidesToShow: 6, slidesToScroll: 6, autoplay: true, autoplaySpeed: 3000, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 4, slidesToScroll: 4 } }, { breakpoint: 768, settings: { slidesToShow: 2, slidesToScroll: 2 } } , { breakpoint: 550, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] },
        initialSize: 0 // not depending on the size of the screen
    },

    {
        el: '.we-makeit-items',
        settings: { dots: false, arrows: false, speed: 300, centerMode: true, autoplay: true, autoplaySpeed: 4000, responsive: [ { breakpoint: 1024, settings: { slidesToShow: 3, slidesToScroll: 3 } }, { breakpoint: 768, settings: { slidesToShow: 2, slidesToScroll: 2 } }, { breakpoint: 550, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] },
        initialSize: 1024
    },

    {
        el: '.our-service-list',
        settings: { dots: false, arrows: false, speed: 300, centerMode: true, responsive: [ { breakpoint: 768, settings: { slidesToShow: 1, slidesToScroll: 1 } } ] },
        initialSize: 768    
    },

    {
        el: '.blog-wrap',
        settings: { dots: false, arrows: false, speed: 300 },
        initialSize: 768
    }           
]);

function

function slickPush(slickEls)
{
    var lastWinSize = 0;

    window.onresize = function(e)
    {
        var winSize = $(window).width();

        /* resize one time */
        if( lastWinSize == winSize)
        {
            return false;
        }

        /* remember last window size */
        lastWinSize = winSize;

        for(var i=0; i<slickEls.length; i++)
        {
            var slickOpts = slickEls[i];

            /* if element not found */
            if( $(slickOpts.el).size() <= 0 )
            {
                continue;
            }

            /* get element */
            var el = $(slickOpts.el);

            /* for all window size */
            if( slickOpts.initialSize == 0 )
            {
                if( typeof slickOpts.object == 'undefined' )
                {
                    slickOpts.object = $(el).slick(slickOpts.settings);
                }

                continue;
            }

            /* destroy slick, if win size more than specified  */
            if( winSize >= slickOpts.initialSize )
            {
                if( typeof slickOpts.object !== 'undefined' )
                {
                    $(slickOpts.object).slick('fuckingDestroy');

                    slickOpts.object = undefined;
                }

                continue;
            }

            /* initial slick */
            if( typeof slickOpts.object == 'undefined' )
            {
                slickOpts.object = $(el).slick(slickOpts.settings);

                // you can change to `refresh` method
            }
        };
    };

    /* run */
    $(window).trigger('resize');    
}   

We had the same problem. It turned out to our own problem: you should avoid to call $('element1').slick(options); multiple times. If you do, then $('element1').slick('unslick') causes problems.

I resolved "cannot read property 'unslick' of undefined" (on line 2299 of slick.js), by adding the following if before attempting to .apply(...)

if (_[i].slick) ret = _[i].slick[opt].apply(_[i].slick, args);

Not sure if this is advisable, but it seems to be working like a champ for now.

I'm pretty sure these issues are all fixed now? I can't find one solid example of an issue from the comments and jsfiddles. - unslicking on breakpoints, and the way to call methods was changed (as someone else mentioned) and also recently a bug with asForNav trying to reference non-existant, or unslicked-sliders was fixed.

This is still an issue with the latest code. If I unslick at a particular breakpoint, reduce the browser width so it "unslicks", but then expand the browser again wider than that breakpoint, it remains unslicked rather than re-slicking.

+1

@flesch91's solution worked for me!

@flesch91 you're a lifesaver! Thank you so much for your solution. It work for me.

@nikitahl May all your dreams come true! ;)

@kenwheeler : I am getting error in IE 9 console because of unslick .
*_when doing $('.responsive').slick('unslick'); getting error - *_

_Unable to get value of the property 'unslick': object is null or undefined_

*_when doing $('.responsive').unslick(); getting error - *_

Object doesn't support property or method 'unslick'
please provide the solution.

@manishagitker or anyone else still experiencing this issue, can you recreate in a fiddle?

The issue is still happening.. i am trying to unslick the slider at a certain breakpoint but its giving me this same error.

Me too. For me works this:

var $slider = $('.slider').slick();
$slider.slick('getSlick').reinit();

@inferusvv, for me too, but new slick dots added every time when using this code (i need to restore slick width on bootstrap tabs change event).

For me works this code:
$slider.slick('unslick').slick(...);

where ... - slick settings varaible.

My way:
`var isSlicked = false

if($(window).width() < 768 && !isSlicked) {
$('.why-chapter__list').slick({
slidesToShow: 1,
slidesToScroll: 1,
prevArrow: gridPrevArrow,
nextArrow: gridNextArrow,
// mobileFirst: true,
// responsive: [{
// breakpoint: 1024,
// settings: 'unslick',
// }],
});
$('.projects__main .grid-menu__list').slick({
slidesToShow: 1,
slidesToScroll: 1,
prevArrow: gridPrevArrow,
nextArrow: gridNextArrow,
centerMode: true,
centerPadding: '0',
});
isSlicked = true;
}
//////////////////////////////////////////
// There's need some way to destroy slick
// and init it in the future may be.
// So, we have var isSlicked which control
// screen size and trigger slider automaticly.
//////////////////////////////////////////
$(window).on('resize orientationchange', function() {
if($(window).width() >= 768 && isSlicked) {
console.log('destroy');
$('.why-chapter__list').slick('unslick');
isSlicked = false;
} else {
if($(window).width() < 768 && !isSlicked) {
$('.why-chapter__list').slick({
slidesToShow: 1,
slidesToScroll: 1,
prevArrow: gridPrevArrow,
nextArrow: gridNextArrow,
// mobileFirst: true,
// responsive: [{
// breakpoint: 1024,
// settings: 'unslick',
// }],
});
$('.projects__main .grid-menu__list').slick({
slidesToShow: 1,
slidesToScroll: 1,
prevArrow: gridPrevArrow,
nextArrow: gridNextArrow,
centerMode: true,
centerPadding: '0',
});
isSlicked = true;
}
}
});`

Okay, guys.... I've tried all above mentioned ways and I still can't get slick slider to work after the page reloads. The slider works perfect until a button is clicked ( for example to update quantity on item) and the slider is gone.... I tried to slick("unslick") and then reinitialize it, still nothing. Anyone ???

Can you provide a codepen or JS Fiddle? @ilkovs

@BryanBarrera , my slick logic is the following. In this case, I'm trying to use the Slider for devices under 1024px. But I also tried in general, still brakes on load. I can't provide fiddle, it's an e-commerce theme (handlebars).

$(document).ready(function(){

function slickify(){
    event.preventDefault();
    $('.cart-list').not('.slick-initialized').slick({
        infinite: false,
        responsive: [
            {
                breakpoint: 1024,
                autoplay: false,
                dots: true,
                infinite: false,
                settings: {
                    slidesToShow: 3,
                    slidesToScroll: 3,
                    dots: true
                }
            },
            {
                breakpoint: 786,
                autoplay: false,
                dots: true,
                infinite: false,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    dots: true
                }
            },
            {
                breakpoint: 550,
                autoplay: false,
                dots: true,
                infinite: false,
                settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1,
                    dots: true
                }
            }
        ]
    });
}

$(window).resize(function(){
    event.preventDefault();
    var $windowWidth = $(window).width();
    if ($windowWidth < 1024) {
        slickify();  

        $(window).resize(function() {
            $('.cart-list').slick('resize');
            event.preventDefault();
          });

          $(window).on('orientationchange', function() {
            $('.cart-list').slick('resize');
            event.preventDefault();
          });
    }
});

});

I tried using any function like 🔽 but nothing seems to fix the issue.

$('body').click(function() {
$('.slider').slick('reInit');
});

As far as destroying and reinitializing I tried the following:

$(document).ready(function() {
$('.cart-list').slick("unslick");
$('.cart-list').slick(");
});

When it loads at 1024 does it load? or on resize it breaks?

@BryanBarrera it loads initially without any issues on any device, but whenever you update something on the page and it reloads with the new values, the slider brakes and I have to manually refresh it again in order to reinitialize.

Do you get any errors in the console?
What version of slick are you using?
Can you try this in the last function you have above?

$('.cart-list').slick(); rather than slick('');

@BryanBarrera the '' is a typo that I did here, but my code is using slick(); sorry about that. I use a CDN instead of uploading the files to the theme. Should be the latest version.

if you add console.log('hey this is a test'); does this load in the console after you update the page and it reloads?

@BryanBarrera it console loges as it should.

solution for unslick on desktops:

  var viewportWidth = $(window).width();
  var slickCheck;
  viewportWidth > 576 ? slickCheck = 'unslick': slickCheck = {slidesToShow: 1};

  $('.my__slider').slick({
    slidesToShow: 1,
    slidesToScroll: 1,
    variableWidth: true,
    arrows: false,
    dots: false,
    mobileFirst: true,
    responsive: [
       {
          breakpoint: 550,
          settings: slickCheck
        }
     ]
  });

I'm not a pro but this is what worked for me.

function myMobileCarousel() {
    var windowSize = jQuery(window).width();
    if (windowSize <= 991) {
        // slick it
        if (!jQuery('.carousel_mobile').hasClass("slick-initialized")) {
            jQuery('.carousel_mobile').slick({
              dots: true,
              infinite: false,
              slide: 'li',
              speed: 800, // was 300
              slidesToShow: 3,
              slidesToScroll: 3,
              responsive: [
                {
                  breakpoint: 991,
                  settings: {
                    slidesToShow: 2,
                    slidesToScroll: 2,
                    infinite: false,
                    dots: true
                  }
                },
                {
                  breakpoint: 767,
                  settings: {
                    slidesToShow: 1,
                    slidesToScroll: 1
                  }
                }
              ]
            });
        }
    } else {
        // unslick
        if (jQuery('.carousel_mobile').hasClass("slick-initialized")) {
            jQuery('.carousel_mobile').slick('unslick');
        }
    }
}

jQuery(document).ready(function(){
    myMobileCarousel();
});

jQuery(window).resize(function(){
    myMobileCarousel();
});

Was this page helpful?
0 / 5 - 0 ratings

Related issues

msavov picture msavov  ·  3Comments

NozX18 picture NozX18  ·  3Comments

crstauf picture crstauf  ·  3Comments

rahi-rajeev picture rahi-rajeev  ·  3Comments

eirikrlee picture eirikrlee  ·  3Comments