Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I run a jQuery function only when it's needed?

I've run into a problem where I have a responsive slider running on my site which has been added to an external .js file. I am running into an issue with a modal not popping up on the homepage because the page is looking for the slider which is only included on a couple of sub pages.

Chrome console is showing the following error: Uncaught TypeError: undefined is not a function

Here is my current code:

$('.my-carousel').slick({
    speed: 330,
    slidesToShow: 4,
});
like image 342
Anthony_Z Avatar asked Dec 19 '22 05:12

Anthony_Z


2 Answers

You can check if plugin has been loaded like this (it checks if given jQuery function exists):

if ($().slick) {
 // .. your code
}

or

if ($.fn.slick) {
 // .. your code
}
like image 107
Indy Avatar answered Dec 21 '22 23:12

Indy


You can just check if the carousel exists before calling the function like so:

var myCarousel = $('.my-carousel');
if (typeof myCarousel.slick !== 'undefined') {
  myCarousel.slick({speed: 330, slidesToShow: 4});
}
like image 36
kis Avatar answered Dec 22 '22 00:12

kis