1

Using this solution, I'm trying to call my plugin's main function only if it exists, however the test fails despite the function actually existing (the plugin works properly on my page).

I changed my code a bit to perform the test first, then call the function anyway. I should see "yes" in the console since the plugin works, instead I see "no".

What am I doing wrong?

if (typeof owlCarousel === 'function') { 
  console.log('yes');
}
else {
  console.log('no');
}
$('.owl-carousel').owlCarousel({
   items: 1
});
drake035
  • 3,955
  • 41
  • 119
  • 229

2 Answers2

0

To test if a jQuery plugin exists, you should check if it's defined in the jQuery namespace

if ( "owlCarousel" in $.fn && typeof $.fn.owlCarousel === "function") {
    $('.owl-carousel').owlCarousel({
        items: 1
    });
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

First, you need to add your code for the owlCarousel, inside the if (true) block, this way its not executing on false.

if (typeof owlCarousel === 'function') { 
  console.log('yes');
  $('.owl-carousel').owlCarousel({
     items: 1
  });
}
else {
  console.log('no');
}

Try wrapping your code inside document ready

$( document ).ready(function() {
       if (typeof owlCarousel === 'function') { 
      console.log('yes');
      $('.owl-carousel').owlCarousel({
         items: 1
      });
    }
    else {
      console.log('no');
    } 
});

to allow for your library, to load first.