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.
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>
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.
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 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.
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:
.update(); // Updates the scrollbar for the instance 'ps' 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.
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:
ps.on('ps-scroll-y', function(y){...})
: Triggered when the vertical scroll position changes. y
provides the vertical scroll position.ps.on('ps-scroll-x', function(x){...})
: Triggered when the horizontal scroll position changes. x
provides the horizontal scroll position.ps.on('ps-scroll-update', function(){...})
: Triggered when the scrollbars are updated (e.g., after calling update()
or when content size changes).ps.on('ps-y-reach-start', function(){...})
: Triggered when the vertical scroll reaches the top.ps.on('ps-y-reach-end', function(){...})
: Triggered when the vertical scroll reaches the bottom.ps.on('ps-x-reach-start', function(){...})
: Triggered when the horizontal scroll reaches the left.ps.on('ps-x-reach-end', function(){...})
: Triggered when the horizontal scroll reaches the right.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:
.on('ps-scroll-y', function(y) {
psconsole.log('Vertical scroll position:', y);
;
})
//Later to remove the listener
.off('ps-scroll-y', function(y) {
psconsole.log('Vertical scroll position:', y);
; })
Remember to replace ps
with your PerfectScrollbar instance.
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.
These options control the overall behavior of Perfect Scrollbar.
minScrollbarLength
(number): Minimum length of the scrollbar thumb in pixels. Defaults to 20.maxScrollbarLength
(number): Maximum length of the scrollbar thumb in pixels. Defaults to null (no maximum).suppressScrollX
(boolean): Suppresses the horizontal scrollbar. Defaults to false
.suppressScrollY
(boolean): Suppresses the vertical scrollbar. Defaults to false
.swipeEasing
(boolean): Enables or disables easing during swipe gestures. Defaults to true
.scrollXMarginOffset
(number): Margin added to the horizontal scrollbar calculation. Useful to avoid scrollbar overlapping content edges. Defaults to 0.scrollYMarginOffset
(number): Margin added to the vertical scrollbar calculation. Useful to avoid scrollbar overlapping content edges. Defaults to 0.These options fine-tune the behavior of the scroll wheel.
wheelSpeed
(number): The speed of scrolling with the mouse wheel. Defaults to 1.wheelPropagation
(boolean): Allows wheel events to propagate to parent elements. Defaults to false
.Perfect Scrollbar allows customization of scrollbar appearance through CSS. However, these options offer basic control over dimensions. Extensive styling should be done through CSS.
scrollbarThickness
(number): Thickness of the scrollbars in pixels. Defaults to 15. Use CSS for more advanced styling.theme
(string): Applies a pre-defined theme. Currently, only ‘dark’ is available; it changes the scrollbar colours. Defaults to null
. Use CSS for more advanced themes.Perfect Scrollbar aims to be accessible. While proper ARIA attributes are applied by default, you can enhance them further:
alwaysVisible
(boolean): Always shows the scrollbar, improving accessibility for some users. Defaults to false
.focus
(boolean): Keep the focus inside of the scrollbar on scroll. Default to false
.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.
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.
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.
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.
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.
.on('ps-y-reach-end', () => {
ps// Load more data when the user reaches the bottom
loadMoreData();
; })
For optimal performance, especially with large amounts of content:
update()
when absolutely necessary. Frequent updates can impact performance.By following these guidelines, you can maintain high performance even when using Perfect Scrollbar with substantial content.
The PerfectScrollbar
constructor creates a new Perfect Scrollbar instance.
Signature:
new PerfectScrollbar(element, options?)
element
(HTMLElement): The DOM element to apply Perfect Scrollbar to. This element should have overflow-y
or overflow-x
set to auto
or scroll
.options
(object, optional): An object containing configuration options (see Configuration Options section). If omitted, default options are used.Return value:
A PerfectScrollbar
instance.
The PerfectScrollbar
instance provides several methods for interacting with the scrollbar.
update()
: Updates the scrollbar dimensions and position based on the current content size. Call this after any changes to the scrollable content that affect its size.destroy()
: Removes the Perfect Scrollbar instance and restores the original element’s behavior.isRtl()
: Returns true
if the scrollbar is in RTL (right-to-left) mode, based on its container’s direction, false
otherwise.isReachingEnd(axis)
: Checks whether the specified axis has reached its end. Accepts 'x'
or 'y'
as parameter.isReachingStart(axis)
: Checks whether the specified axis has reached its start. Accepts 'x'
or 'y'
as parameter.getScrollTop()
: Returns the vertical scroll position.setScrollTop(top)
: Sets the vertical scroll position. top
is the number of pixels from the top.getScrollLeft()
: Returns the horizontal scroll position.setScrollLeft(left)
: Sets the horizontal scroll position. left
is the number of pixels from the left.getSelectionStart()
: Returns the start position of the text selection inside the scrollable element.getSelectionEnd()
: Returns the end position of the text selection inside the scrollable element.scrollTo(x, y, speed?)
: Scrolls to a specific position. x
and y
are the target horizontal and vertical positions (pixels). speed
is an optional value for animation speed (milliseconds).scrollToTop(speed?)
: Scrolls to the top of the container. speed
is an optional value for animation speed (milliseconds).scrollToBottom(speed?)
: Scrolls to the bottom of the container. speed
is an optional value for animation speed (milliseconds).scrollTop(speed?)
: Sets the vertical scroll position. If no argument is provided, it returns the current vertical scroll position. speed
is an optional value for animation speed (milliseconds).scrollLeft(speed?)
: Sets the horizontal scroll position. If no argument is provided, it returns the current horizontal scroll position. speed
is an optional value for animation speed (milliseconds).on(eventName, handler)
: Attaches an event listener.off(eventName, handler)
: Removes an event listener.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.
While Perfect Scrollbar doesn’t expose many direct public properties for modification, the following can be considered:
element
(read-only): The DOM element the PerfectScrollbar instance is attached to.options
(read-only): Contains the configuration options used during initialization (a copy, not the original object passed in the constructor). You cannot modify it directly to change settings. To change a setting, you’ll need to destroy and re-initialize the Perfect Scrollbar.Scrollbar not appearing: Ensure that the target element has sufficient content to necessitate a scrollbar (height or width exceeding the container’s dimensions) and that overflow-y
or overflow-x
is set to auto
or scroll
. Double-check that Perfect Scrollbar is correctly initialized and that no CSS rules are overriding the scrollbar’s display. Also verify that suppressScrollX
or suppressScrollY
options aren’t unintentionally disabling the scrollbar.
Scrollbar jumping or behaving erratically: This often points to issues with dynamic content updates. Ensure you’re calling update()
after any changes to the scrollable content’s size or structure. Incorrectly sized or positioned content can lead to these problems. Check for conflicts with other JavaScript libraries that might be manipulating the DOM element.
Scrollbar styling issues: Styling problems are usually due to CSS conflicts. Inspect the generated CSS classes to identify which styles are being applied and check for conflicting styles in your own CSS rules. Ensure your CSS is correctly targeting the appropriate Perfect Scrollbar classes, and use the browser’s developer tools to debug CSS specificity and cascading issues. Remember that changing the styling significantly might require adjusting scrollbarThickness
or other relevant configuration options to ensure proper layout.
Performance issues: If scrolling is slow or laggy, especially with large amounts of content, refer to the Performance Optimization section of this manual. Consider using virtualization techniques or optimizing your DOM updates for improved performance.
Events not firing: Verify that you’ve correctly attached event listeners using the on()
method and that the event names match the documented events. Use the browser’s developer tools to check for JavaScript errors that might prevent event handlers from executing.
Browser developer tools: Use your browser’s developer tools (usually accessed by pressing F12) to inspect the HTML and CSS generated by Perfect Scrollbar. This helps identify styling conflicts or unexpected changes to the DOM. The console can also display any JavaScript errors that might be preventing Perfect Scrollbar from functioning correctly.
Simplify the HTML: Create a minimal, reproducible example to isolate the problem. Reduce your HTML structure to the essential components involved and try to reproduce the issue in this simplified environment.
Check the console for errors: The browser’s JavaScript console will display any errors encountered during Perfect Scrollbar initialization or execution. Address these errors first as they often provide valuable clues about the problem’s root cause.
Inspect the generated HTML and CSS: Carefully inspect the HTML structure and CSS styles applied by Perfect Scrollbar to ensure they’re consistent with expectations. Look for any unexpected classes or styles that might be causing the issue.
Test in different browsers: Test your implementation across multiple browsers to identify browser-specific issues and ensure cross-browser compatibility.
Complex DOM manipulations: While Perfect Scrollbar adapts to many dynamic situations, excessively complex or rapidly changing DOM structures might challenge its performance or lead to unexpected behavior. Consider optimizing your DOM updates or exploring alternative approaches for managing highly dynamic content.
CSS transformations: Applying CSS transforms (e.g., translate
, scale
) directly to the scrollable container might interfere with Perfect Scrollbar’s calculations, leading to inaccurate scrollbar positions or behavior. Adjust the approach to avoid direct transformations on the container or carefully consider how to integrate them with Perfect Scrollbar’s update mechanism.
Iframe integration: While possible, integrating Perfect Scrollbar with iframes requires additional attention. Ensure that the iframe’s content is fully loaded before initializing Perfect Scrollbar to avoid issues. You might need to use message passing or other techniques to coordinate between the parent page and the iframe.
Compatibility with certain CSS frameworks: While Perfect Scrollbar strives for broad compatibility, it’s possible that certain CSS frameworks or styles might conflict with its internal workings. In such cases, carefully analyze CSS conflicts and adjust your styles or framework configuration as needed.
Keep in mind that these limitations are subject to change with updates to Perfect Scrollbar. Always consult the latest documentation for the most current information.
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.
Clone the repository: Start by cloning the Perfect Scrollbar repository to your local machine:
git clone https://github.com/your-repo-link.git
Install dependencies: Navigate to the cloned directory and install the necessary dependencies using npm or yarn:
npm install
# or
yarn install
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
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.
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.
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.
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
Make your changes: Implement your changes, ensuring they adhere to the coding style guide and pass all tests and lint checks.
Commit your changes: Commit your changes with descriptive commit messages:
git add .
git commit -m "Add a clear and concise message describing your changes"
Push your branch: Push your branch to the remote repository:
git push origin my-feature-branch
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.
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.