Search code examples
javascriptlaravellaravel-mixperfect-scrollbar

Laravel javascript require perfect-scrollbar


I try to require the jquery pulgin perfect-scrollbar to my laravel javascript. So I have runed

npm install perfect-scrollbar

In Line 1 of my Javascript file (located under ressources/assets/javascript/material-dashboard/myfile.js) I require the plugin with this attempt

require('perfect-scrollbar');

The myscript.js is required to the app.js with require('./material-dashboard/myscript.js')

Now the browser console tell me

Uncaught TypeError: $(...).perfectScrollbar is not a function

The assets are compiled with

npm run dev

The content of myscript.js

require('perfect-scrollbar');

(function() {
  isWindows = navigator.platform.indexOf('Win') > -1 ? true : false;

  if (isWindows) {
    // if we are on windows OS we activate the perfectScrollbar function
    $('.sidebar .sidebar-wrapper, .main-panel').perfectScrollbar();

    $('html').addClass('perfect-scrollbar-on');
  } else {
    $('html').addClass('perfect-scrollbar-off');
  }
})();

What is wrong?

Thanks for your help!


Solution

  • As per the docs, to initialise an element with the plugin you should do something like the following:

    import PerfectScrollbar from 'perfect-scrollbar';
    
    new PerfectScrollbar(".sidebar .sidebar-wrapper");
    new PerfectScrollbar(".main-panel");
    

    If you want to use require instead of import you would do something like:

    let PerfectScrollbar = require('perfect-scrollbar').default;
    

    Lastly, it doesn't look like the plugin is meant to work with jQuery out of the box, however, if you want to use with jQuery like you are in your post you could do the following:

    import PerfectScrollbar from 'perfect-scrollbar';
    
    $.fn.perfectScrollbar = function (options) {
    
        return this.each((k, elm) => new PerfectScrollbar(elm, options || {}));
    };
    
    $('.sidebar .sidebar-wrapper, .main-panel').perfectScrollbar();