Anthony_Z
Anthony_Z

Reputation: 725

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,
});

Upvotes: 4

Views: 5954

Answers (5)

Priyanka Singh
Priyanka Singh

Reputation: 11

You can apply slick only if it is not applied, doing something like below:

$('.my-carousel').not('.slick-initialized').slick({
  // Your settings here.
});

Upvotes: 1

kis
kis

Reputation: 21

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});
}

Upvotes: 1

Indy
Indy

Reputation: 4957

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
}

Upvotes: 12

Yami
Yami

Reputation: 1425

if($('.my-carousel').length){
   $('.my-carousel').slick({
      speed: 330,
      slidesToShow: 4,
   });
}

Upvotes: -1

Tommy Jinks
Tommy Jinks

Reputation: 757

You could use length to check if it exists, for example:

if ($('.my-element').length) { //do stuff }

Upvotes: 0

Related Questions