perfect-scrollbar - Documentation

Getting Started

Installation

Perfect Scrollbar can be installed via npm or yarn:

npm install perfect-scrollbar
# or
yarn add perfect-scrollbar

Alternatively, you can include it via a CDN. A convenient option is jsDelivr:

<link href="https://cdn.jsdelivr.net/npm/perfect-scrollbar@latest/css/perfect-scrollbar.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/perfect-scrollbar@latest/dist/perfect-scrollbar.min.js"></script>

Remember to replace @latest with a specific version number if needed for better reproducibility.

Basic Usage

After installation, include the CSS file and then initialize Perfect Scrollbar on your scrollable element. This typically involves selecting the element with JavaScript and calling the PerfectScrollbar constructor. The constructor accepts a single argument: the DOM element you want to make scrollable.

For example, if your scrollable element has the ID “my-scroll-container”:

import PerfectScrollbar from 'perfect-scrollbar';

const scrollbar = new PerfectScrollbar('#my-scroll-container');

If using a CDN, ensure the script is included after the element you are targeting:

<div id="my-scroll-container">
  <!-- Scrollable content here -->
</div>
<script src="https://cdn.jsdelivr.net/npm/perfect-scrollbar@latest/dist/perfect-scrollbar.min.js"></script>
<script>
  const scrollbar = new PerfectScrollbar('#my-scroll-container');
</script>

Quick Example

This example shows a basic implementation with a simple scrollable div:

<!DOCTYPE html>
<html>
<head>
  <title>Perfect Scrollbar Example</title>
  <link href="https://cdn.jsdelivr.net/npm/perfect-scrollbar@latest/css/perfect-scrollbar.min.css" rel="stylesheet">
  <style>
    #my-scroll-container {
      height: 200px;
      overflow-y: auto;
    }
  </style>
</head>
<body>
  <div id="my-scroll-container">
    <p>This is some text.</p>
    <p>More text here.</p>
    <p>Even more text to make the scrollbar appear.</p>
    <p>And more...</p>
    <p>Lots and lots of text!</p>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/perfect-scrollbar@latest/dist/perfect-scrollbar.min.js"></script>
  <script>
    new PerfectScrollbar('#my-scroll-container');
  </script>
</body>
</html>

This will create a scrollable div with Perfect Scrollbar functionality. Remember to adjust the height of the container to ensure a scrollbar is visible.

Core Concepts

Scrollbar Structure

Perfect Scrollbar adds two scrollbars to your designated container: a vertical scrollbar and a horizontal scrollbar (if needed). These scrollbars are not native browser scrollbars; they are custom elements rendered by Perfect Scrollbar, allowing for greater styling control and consistent behavior across different browsers. The structure generally includes:

Initialization

Initialization is the process of creating a Perfect Scrollbar instance for a specific DOM element. This is done by using the PerfectScrollbar constructor, passing the target element as an argument. The constructor returns a Perfect Scrollbar instance, allowing for further interaction and configuration. For example:

import PerfectScrollbar from 'perfect-scrollbar';

const ps = new PerfectScrollbar('#myElement'); // Initialize on element with ID 'myElement'

or, if you are using a querySelectorAll for multiple elements:

import PerfectScrollbar from 'perfect-scrollbar';
document.querySelectorAll('.my-elements').forEach(element => {
    new PerfectScrollbar(element);
});

After initialization, Perfect Scrollbar automatically calculates the dimensions of the content and renders the scrollbars accordingly.

Updating the Scrollbar

After initializing Perfect Scrollbar, you might need to update it if the content within the scrollable area changes dynamically (e.g., adding or removing elements, changing content size). This prevents the scrollbar from showing incorrect positions or dimensions. You can update the scrollbar using the update() method:

ps.update(); // Updates the scrollbar for the instance 'ps'

It’s crucial to call update() after changes affecting the scrollable content’s dimensions or size. Failing to do so can lead to visual inconsistencies and incorrect scrolling behavior.

Event Handling

Perfect Scrollbar provides several events that you can listen for to respond to scrolling actions or changes in scroll position. These events are dispatched on the Perfect Scrollbar instance. Here are some common events and how to listen for them:

To remove an event listener, use ps.off('event-name', listenerFunction) replacing event-name with the event name and listenerFunction with the corresponding function. For example:

ps.on('ps-scroll-y', function(y) {
  console.log('Vertical scroll position:', y);
});

//Later to remove the listener
ps.off('ps-scroll-y', function(y) {
  console.log('Vertical scroll position:', y);
});

Remember to replace ps with your PerfectScrollbar instance.

Configuration Options

Perfect Scrollbar offers a wide range of configuration options to customize its behavior and appearance. These options can be passed as a second argument to the PerfectScrollbar constructor. If not provided, default values are used.

General Options

These options control the overall behavior of Perfect Scrollbar.

Wheel Options

These options fine-tune the behavior of the scroll wheel.

Scrollbar Styling Options

Perfect Scrollbar allows customization of scrollbar appearance through CSS. However, these options offer basic control over dimensions. Extensive styling should be done through CSS.

Accessibility Options

Perfect Scrollbar aims to be accessible. While proper ARIA attributes are applied by default, you can enhance them further:

Plugins

Perfect Scrollbar supports plugins to extend its functionality. Plugins usually add or modify behavior. For detailed information on available plugins and their usage, refer to the plugins section of the Perfect Scrollbar documentation (if available). Integrating plugins typically involves including the plugin script and potentially configuring options specific to that plugin.

Advanced Usage

Customizing Scrollbar Appearance

While Perfect Scrollbar provides some basic configuration options for scrollbar thickness and theme, extensive customization is best achieved through CSS. You can target the specific CSS classes generated by Perfect Scrollbar to modify the appearance of the scrollbar tracks, thumbs, and other elements. Inspect the generated HTML and CSS to identify the relevant classes. Remember that class names might change between versions, so always check the current version’s generated code for accurate class names. Consider using a CSS preprocessor (like Sass or Less) for better organization and maintainability of your styles.

Working with Multiple Scrollbars

Perfect Scrollbar can be easily used with multiple scrollable elements on a single page. Simply initialize a new PerfectScrollbar instance for each element. Each instance is independent, allowing for different configurations and behaviors. For example:

import PerfectScrollbar from 'perfect-scrollbar';

const ps1 = new PerfectScrollbar('#scroll-container-1');
const ps2 = new PerfectScrollbar('#scroll-container-2', { suppressScrollX: true }); // Different configuration

Remember that calling update() on each instance is important if the content of those elements changes.

Integration with Other Libraries

Integrating Perfect Scrollbar with other JavaScript libraries is generally straightforward. However, ensure that there are no conflicts between the libraries, especially concerning event handling. Consider the order of inclusion and initialization, ensuring Perfect Scrollbar is initialized after any library that might modify the DOM elements it targets. If conflicts arise, you might need to adjust event handling or use techniques like event delegation to avoid overlapping behavior.

Handling Different Scroll Events

Perfect Scrollbar offers various events (detailed in the Core Concepts section). You can listen to events like ps-scroll-y, ps-scroll-x, ps-scroll-update, ps-y-reach-start, ps-y-reach-end, etc., to handle specific scrolling events. For example, you can trigger actions when a user reaches the bottom of a scroll area or when the scrollbar updates. This allows implementing features like infinite scrolling, lazy loading, or custom scroll indicators.

ps.on('ps-y-reach-end', () => {
  // Load more data when the user reaches the bottom
  loadMoreData();
});

Performance Optimization

For optimal performance, especially with large amounts of content:

By following these guidelines, you can maintain high performance even when using Perfect Scrollbar with substantial content.

API Reference

Constructor

The PerfectScrollbar constructor creates a new Perfect Scrollbar instance.

Signature:

new PerfectScrollbar(element, options?)

Return value:

A PerfectScrollbar instance.

Methods

The PerfectScrollbar instance provides several methods for interacting with the scrollbar.

Events

The PerfectScrollbar instance dispatches several custom events. (See Core Concepts -> Event Handling for details). These events allow you to respond to scrolling actions and changes in the scroll position. Use the .on() method to attach listeners to these events.

Properties

While Perfect Scrollbar doesn’t expose many direct public properties for modification, the following can be considered:

Troubleshooting

Common Issues

Debugging Tips

Known Limitations

Contributing

We welcome contributions to Perfect Scrollbar! Whether it’s fixing bugs, adding features, or improving documentation, your help is valuable. Before contributing, please take a moment to read through these guidelines.

Setting up the Development Environment

  1. Clone the repository: Start by cloning the Perfect Scrollbar repository to your local machine:

    git clone https://github.com/your-repo-link.git
  2. Install dependencies: Navigate to the cloned directory and install the necessary dependencies using npm or yarn:

    npm install
    # or
    yarn install
  3. Start the development server: Perfect Scrollbar likely uses a development server (e.g., webpack-dev-server) for development. Consult the project’s README for instructions on starting the server. This typically involves running a command like:

    npm start
    # or
    yarn start
  4. Build the project: To create a production-ready build, run the build command as specified in the README, usually something like:

    npm run build
    # or
    yarn build

This will generate the compiled JavaScript and CSS files.

Coding Style Guide

Adhere to the project’s existing coding style. Consistency is important for maintainability. Check the project’s README or .editorconfig file for details about the preferred coding style (e.g., indentation, naming conventions, etc.). Generally, follow standard JavaScript best practices.

Testing and Linting

Perfect Scrollbar likely uses testing frameworks (e.g., Jest, Mocha) and linting tools (e.g., ESLint) to maintain code quality. Before submitting a pull request, ensure your changes pass all existing tests and lint checks. Run the testing and linting commands as specified in the README, typically something like:

npm test
# or
yarn test

npm run lint
# or
yarn lint

Address any reported errors or warnings before proceeding.

Submitting Pull Requests

  1. Create a branch: Create a new branch from the main or develop branch (check the project’s default branch) for your changes:

    git checkout -b my-feature-branch
  2. Make your changes: Implement your changes, ensuring they adhere to the coding style guide and pass all tests and lint checks.

  3. Commit your changes: Commit your changes with descriptive commit messages:

    git add .
    git commit -m "Add a clear and concise message describing your changes"
  4. Push your branch: Push your branch to the remote repository:

    git push origin my-feature-branch
  5. Create a pull request: Create a pull request on the GitHub repository. Provide a clear description of your changes and address any feedback provided by the maintainers. Remember to include a link to any relevant issues. A well-written pull request description significantly increases the chances of your contribution being accepted.

Remember to replace placeholders like your-repo-link, my-feature-branch, etc., with the appropriate values from the project’s repository. Always refer to the project’s README file for the most up-to-date and specific instructions.

License

Perfect Scrollbar is typically licensed under the MIT License. This means you are free to use, modify, and distribute Perfect Scrollbar in your projects, both commercial and non-commercial, subject to the terms and conditions of the MIT License. A copy of the MIT License should be included with the project’s source code. You are responsible for complying with the terms of the MIT License. Always refer to the LICENSE file included with the distribution for the complete and legally binding license text.