Magento 2 – Fix ReferenceError: jQuery is Not Defined in Owl Carousel Slider

jquerymagento2

I am trying to use slider in my magneto custom module

I did Following steps:

1 create a file requirejs-config.js

var config = {
    map: {
        '*': {
            my: 'Vendor_Module/js/owl.carousel',
        }
    }
};
  1. created a owl.carousle.js fine in web/js

    jQuery(document).ready(function($) {
    var owl = $("#owl-demo1");
         owl.owlCarousel({
        // Most important owl features
    margin:10,       
    items : 4,
    itemsCustom : false,
    itemsDesktop : [1199,2],
    itemsDesktopSmall : [900,4],
    itemsTablet: [768,3],
    itemsTabletSmall: [700,2],
    itemsMobile : [479,1],
    
    
    singleItem : false,
    itemsScaleUp : false,
    
    
    //Basic Speeds
    slideSpeed : 200,
    paginationSpeed : 800,
    rewindSpeed : 1000,
    
    //Autoplay
    autoPlay : true,
    stopOnHover : false,
    
    // Navigation
    navigation : true,
    navigationText: ["Left","Right"],
    rewindNav : true,
    scrollPerPage : true,
    
    
    // Responsive 
    responsive: true,
    responsiveRefreshRate : 200,
    responsiveBaseWidth: window,
    
    
    
    //Mouse Events
    dragBeforeAnimFinish : true,
    mouseDrag : true,
    touchDrag : true,
    
    
    
    });
    });
    

The slider is not working giving an error in the console

ReferenceError: jQuery is not defined error

Best Answer

Replace your requirejs-config.js with the below code

var config = {
paths: {
    'my': 'Vendor_Module/js/owl.carousel'
},
 shim: {
    'my': {
        deps: ['jquery']
    },
}
};

and then wherever you're calling this js you'd call like below

require(['jquery','my'],function($){
    $(document).ready(function(){

        // the below must be as per your requirement

        $("#owl-demo").owlCarousel({
            navigation : true,
            autoplay: true,
            autoplayHoverPause: false,
            autoplaySpeed: 2000,
            loop: true,
            smartSpeed: 450
          });
    });
});

Hope this helps.