- ×
A javascript scrollbar plugin which hides native scrollbars, provides custom styleable overlay scrollbars and keeps the native functionality and feeling.
Filed under user interface
OverlayScrollbars
OverlayScrollbars is a javascript scrollbar plugin that hides native scrollbars, provides custom styleable overlay scrollbars and keeps the native functionality and feeling.
Why
I created this plugin because I hate ugly and space consuming scrollbars. Similar plugins haven't met my requirements in terms of features, quality, simplicity, license or browser support.
Goals & Features
- Simple, powerful and well documented API
- High browser compatibility - Firefox 59+, Chrome 55+, Opera 42+, Edge 12+, Safari 10+ and IE 11
- Can be run on the server - SSR, SSG and ISR support
- Tested on various devices - Mobile, Desktop and Tablet
- Tested with various (and mixed) inputs - Mouse, Touch and Pen
- Treeshaking - bundle only what you really need
- Automatic update detection - no polling
- Usage of latest browser features - best performance in new browsers
- Bidirectional - LTR or RTL direction support
- Supports usage on the
body
element - Supports all virtual scrolling libraries
- Simple and effective scrollbar styling
- Highly customizable
- TypeScript support - fully written in TypeScript
- Dependency free - 100% self written to ensure small size and best functionality
- High quality and fully typed framework versions for
react
,vue
,angular
,svelte
andsolid
.
Choose your framework
Additionally to the vanilla JavaScript version you can use the official framework components & utilities:
Getting started
npm & nodejs
OverlayScrollbars can be downloaded from npm or the package manager of your choice:
npm install overlayscrollbars
After installation it can be imported:
import 'overlayscrollbars/overlayscrollbars.css'; import { OverlayScrollbars, ScrollbarsHidingPlugin, SizeObserverPlugin, ClickScrollPlugin } from 'overlayscrollbars';
Note: In older nodejs versions use
'overlayscrollbars/styles/overlayscrollbars.css'
as the import path for the CSS file.Manual download & embedding
You can use OverlayScrollbars without any bundler or package manager.
Simply download it from the Releases or use a CDN.- Use the javascript files with the
.browser
extension. - Use the javascript files with the
.es5
extension if you need to support older browsers like IE11, otherwise use the.es6
files. - For production use the javascript / stylesheet files with the
.min
extension.
Embedd OverlayScrollbars manually in your HTML:
<link type="text/css" href="path/to/overlayscrollbars.css" rel="stylesheet" /> <script type="text/javascript" src="path/to/overlayscrollbars.browser.es.js" defer></script>
You can then use the global variable
OverlayScrollbarsGlobal
to access the api similar to how you can do it in nodejs / modules:var { OverlayScrollbars, ScrollbarsHidingPlugin, SizeObserverPlugin, ClickScrollPlugin } = OverlayScrollbarsGlobal;
The examples in this documentation will use the
import
syntax instead of theOverlayScrollbarsGlobal
object. Both versions are equivalent though.Initialization
Note: During initialization its expected that the CSS file is loaded and parsed by the browser.
You can initialize either directly with an
Element
or with anObject
where you have more control over the initialization process.// simple initialization with an element const osInstance = OverlayScrollbars(document.querySelector('#myElement'), {});
Bridging initialization flickering
If you initialize OverlayScrollbars it needs a few milliseconds to create and append all the elements to the DOM. While this period the native scrollbars are still visible and are switched out after the initialization is finished. This is perceived as flickering.
To fix this behavior apply the
data-overlayscrollbars-initialize
attribute to the target element (andhtml
element if the target element isbody
).<!-- for the body element --> <html data-overlayscrollbars-initialize> <head></head> <body data-overlayscrollbars-initialize></body> </html> <!-- for all other elements --> <div data-overlayscrollbars-initialize> OverlayScrollbars is applied to this div </div>
Initialization with an Object
This is a in depth topic. Click here to read it.
> Note: For now please refer to the TypeScript definitions for a more detailed description of all possibilities. The only required field is thetarget
field. This is the field to which the plugin is applied to.
If you use the object initialization only with thetarget
field, the outcome is equivalent to the element initialization:js // Both initializations have the same outcome OverlayScrollbars(document.querySelector('#myElement'), {}); OverlayScrollbars({ target: document.querySelector('#myElement') }, {});
In the initialization object you can specify how the library is handling generated elements. For example you can appoint an existing element as theviewport
element. Like this the library won't generate it but take the specified element instead:js OverlayScrollbars({ target: document.querySelector('#target'), elements: { viewport: document.querySelector('#viewport'), }, }, {});
This is very useful if you have a fixed DOM structure and don't want OverlayScrollbars to generate its own elements. Those cases arise very often when you want an other library to work together with OverlayScrollbars. --- You can also decide to which element the scrollbars should be applied to:js OverlayScrollbars({ target: document.querySelector('#target'), scrollbars: { slot: document.querySelector('#target').parentElement, }, }, {});
--- And last but not least you can decide when the initialization should be canceled:js OverlayScrollbars({ target: document.querySelector('#target'), cancel: { nativeScrollbarsOverlaid: true, body: null, } }, {});
In the above example the initialization is canceled when the native scrollbars are overlaid or when your target is abody
element and the plugin determined that a initialization to thebody
element would affect native functionality likewindow.scrollTo
.Options
You can initialize OverlayScrollbars with an initial set of options, which can be changed at any time with the
options
method:OverlayScrollbars(document.querySelector('#myElement'), { overflow: { x: 'hidden', }, });
Options in depth
This is a in depth topic. Click here to read it.
The default options are:js const defaultOptions = { paddingAbsolute: false, showNativeOverlaidScrollbars: false, update: { elementEvents: [['img', 'load']], debounce: [0, 33], attributes: null, ignoreMutation: null, }, overflow: { x: 'scroll', y: 'scroll', }, scrollbars: { theme: 'os-theme-dark', visibility: 'auto', autoHide: 'never', autoHideDelay: 1300, dragScroll: true, clickScroll: false, pointers: ['mouse', 'touch', 'pen'], }, };
###paddingAbsolute
| type | default | | :--- | :--- | |boolean
|false
| Indicates whether the padding for the content shall be absolute. ###showNativeOverlaidScrollbars
| type | default | | :--- | :--- | |boolean
|false
| Indicates whether the native overlaid scrollbars shall be visible. ###update.elementEvents
| type | default | | :--- | :--- | |Array<[string, string]> \| null
|[['img', 'load']]
| An array of tuples. The first value in the tuple is anselector
and the second value areevent names
. The plugin will update itself if any of the elements with the specified selector will emit any specified event. The default value can be interpreted as "The plugin will update itself if anyimg
element emits anload
event." ###update.debounce
| type | default | | :--- | :--- | |[number, number] \| number \| null
|[0, 33]
| > Note: If 0 is used for the timeout,requestAnimationFrame
instead ofsetTimeout
is used for the debounce. Debounces theMutationObserver
which tracks changes to the content. If a tuple is passed, the first value is the timeout and second is the max wait. If only a number is passed you specify only the timeout and there is no max wait. With null there is no debounce. Usefull to fine-tune performance. ###update.attributes
| type | default | | :--- | :--- | |string[] \| null
|null
| > Note: There is a base array of attributes that theMutationObserver
always observes, even if this option isnull
. An array of additional attributes that theMutationObserver
should observe for the content. ###update.ignoreMutation
| type | default | | :--- | :--- | |((mutation) => any) \| null
|null
| A function which receives aMutationRecord
as an argument. If the function returns a truthy value the mutation will be ignored and the plugin won't update. Usefull to fine-tune performance. ###overflow.x
| type | default | | :--- | :--- | |string
|'scroll'
| > Note: Valid values are:'hidden'
,'scroll'
,'visible'
,'visible-hidden'
and'visible-scroll'
. The overflow behavior for the horizontal (x) axis. ###overflow.y
| type | default | | :--- | :--- | |string
|'scroll'
| > Note: Valid values are:'hidden'
,'scroll'
,'visible'
,'visible-hidden'
and'visible-scroll'
. The overflow behavior for the vertical (y) axis. ###scrollbars.theme
| type | default | | :--- | :--- | |string \| null
|'os-theme-dark'
| Applies the specified theme (classname) to the scrollbars. ###scrollbars.visibility
| type | default | | :--- | :--- | |string
|'auto'
| > Note: Valid values are:'visible'
,'hidden'
, and'auto'
. The base visibility of the scrollbars. ###scrollbars.autoHide
| type | default | | :--- | :--- | |string
|'never'
| > Note: Valid values are:'never'
,'scroll'
,'leave'
and'move'
. The possibility to hide visible scrollbars automatically after a certain user action. ###scrollbars.autoHideDelay
| type | default | | :--- | :--- | |number
|1300
| The delay in milliseconds before the scrollbars are hidden automatically. ###scrollbars.dragScroll
| type | default | | :--- | :--- | |boolean
|true
| Indicates whether you can drag the scrollbar handles for scrolling. ###scrollbars.clickScroll
| type | default | | :--- | :--- | |boolean
|false
| > Note: This options requires the ClickScrollPlugin to work. Indicates whether you can click on the scrollbar track for scrolling. ###scrollbars.pointers
| type | default | | :--- | :--- | |string[] \| null
|['mouse', 'touch', 'pen']
| ThePointerTypes
the plugin should react to.Events
You can initialize OverlayScrollbars with an initial set of events, which can be managed at any time with the
on
andoff
methods:OverlayScrollbars(document.querySelector('#myElement'), {}, { updated(osInstance, onUpdatedArgs) { // ... } });
Events in depth
This is a in depth topic. Click here to read it.
> Note: Every event receives theinstance
from which it was invoked as the first argument. Always. ###initialized
| arguments | description | | :--- | :--- | |instance
| The instance which invoked the event. | Is invoked after all generated elements, observers and events were appended to the DOM. ###updated
| arguments | description | | :--- | :--- | |instance
| The instance which invoked the event. | |onUpdatedArgs
| Anobject
which describes the update in detail. | > Note: If an update was triggered but nothing changed, the event won't be invoked. Is invoked after the instace was updated. ###destroyed
| arguments | description | | :--- | :--- | |instance
| The instance which invoked the event. | |canceled
| Anboolean
which indicates whether the initialization was canceled and thus destroyed. | Is invoked after all generated elements, observers and events were removed from the DOM. ###scroll
| arguments | description | | :--- | :--- | |instance
| The instance which invoked the event. | |event
| The originalevent
argument of the DOM event. | Is invoked by scrolling the viewport.Instance
Note: For now please refer to the TypeScript definitions for a more detailed description.
interface OverlayScrollbars { options(): Options; options(newOptions: PartialOptions, pure?: boolean): Options; on(eventListeners: EventListeners, pure?: boolean): () => void; on<N extends keyof EventListenerArgs>(name: N, listener: EventListener<N>): () => void; on<N extends keyof EventListenerArgs>(name: N, listener: EventListener<N>[]): () => void; off<N extends keyof EventListenerArgs>(name: N, listener: EventListener<N>): void; off<N extends keyof EventListenerArgs>(name: N, listener: EventListener<N>[]): void; update(force?: boolean): boolean; state(): State; elements(): Elements; destroy(): void; }
Static Methods
Note: For now please refer to the TypeScript definitions for a more detailed description.
interface OverlayScrollbarsStatic { (target: InitializationTarget): OverlayScrollbars | undefined; (target: InitializationTarget, options: PartialOptions, eventListeners?: EventListeners): OverlayScrollbars; plugin(plugin: Plugin | Plugin[]): void; valid(osInstance: any): osInstance is OverlayScrollbars; env(): Environment; }
Styling
OverlayScrollbars comes with two themes called
os-theme-dark
andos-theme-light
. You can use thescrollbars.theme
option to change the theme.Custom themes can be done in multiple ways. The easiest and fastest is to use the predefined set of
CSS Custom Properties
aka. CSS variables. In case those aren't enought you can add custom class names or add custom styling to the existing class names.Styling in depth
This is a in depth topic. Click here to read it.
### CSS Custom properties OverlayScrollbars provides a set ofCSS Custom Properties
which makes scrollbar styling easy and fast:scss .os-scrollbar { // The size of the scrollbar --os-size: 0; // The axis-perpedicular padding of the scrollbar (horizontal: padding-y, vertical: padding-x) --os-padding-perpendicular: 0; // The axis padding of the scrollbar (horizontal: padding-x, vertical: padding-y) --os-padding-axis: 0; // The border radius of the scrollbar track --os-track-border-radius: 0; // The background of the scrollbar track --os-track-bg: none; // The :hover background of the scrollbar track --os-track-bg-hover: none; // The :active background of the scrollbar track --os-track-bg-active: none; // The border of the scrollbar track --os-track-border: none; // The :hover background of the scrollbar track --os-track-border-hover: none; // The :active background of the scrollbar track --os-track-border-active: none; // The border radius of the scrollbar handle --os-handle-border-radius: 0; // The background of the scrollbar handle --os-handle-bg: none; // The :hover background of the scrollbar handle --os-handle-bg-hover: none; // The :active background of the scrollbar handle --os-handle-bg-active: none; // The border of the scrollbar handle --os-handle-border: none; // The :hover border of the scrollbar handle --os-handle-border-hover: none; // The :active border of the scrollbar handle --os-handle-border-active: none; // The min size of the scrollbar handle --os-handle-min-size: 33px; // The max size of the scrollbar handle --os-handle-max-size: none; // The axis-perpedicular size of the scrollbar handle (horizontal: height, vertical: width) --os-handle-perpendicular-size: 100%; // The :hover axis-perpedicular size of the scrollbar handle (horizontal: height, vertical: width) --os-handle-perpendicular-size-hover: 100%; // The :active axis-perpedicular size of the scrollbar handle (horizontal: height, vertical: width) --os-handle-perpendicular-size-active: 100%; // Increases the interactive area of the scrollbar handle. --os-handle-interactive-area-offset: 0; }
You can alter the properties either for both scrollbars at once or per scrollbar axis. In the example below I've chosenos-theme-custom
as the theme name:scss // horizontal and vertical scrollbar are 10px .os-theme-custom { --os-size: 10px; } // horizontal scrollbar is 10px .os-theme-custom.os-scrollbar-horizontal { --os-size: 10px; } // vertical scrollbar is 20px .os-theme-custom.os-scrollbar-vertical { --os-size: 20px; }
You can then use your theme by assigning it via thescrollbars.theme
option:js OverlayScrollbars(document.body, { scrollbars: { theme: 'os-theme-custom' } });
Since scrollbar styles are usually simple, this set of options should be enough to get your desired styling. In case you need more freedom you can create your own styles by adding styling to the base class names described in the next section. ### Scrollbars structure and CSS class names The scrollbars HTML markup looks like:html <div class="os-scrollbar os-scrollbar-horizontal"> <div class="os-scrollbar-track"> <div class="os-scrollbar-handle"> </div> </div> </div> <div class="os-scrollbar os-scrollbar-vertical"> <div class="os-scrollbar-track"> <div class="os-scrollbar-handle"> </div> </div> </div>
The class names are simplified, in a real application the.os-scrollbar
element can have additional class names which modify the appearance (mostly visibility and alignment).
Below is a list of the most important class names you will encounter: | CSS class name | description | | :--- | :--- | |.os-scrollbar
| The root element of a scrollbar. | |.os-scrollbar-rtl
| Indicates aRTL
direction of the host element the scrollbar belongs to. | |.os-scrollbar-horizontal
| The root element of a horizontal scrollbar. | |.os-scrollbar-vertical
| The root element of a vertical scrollbar. | |.os-scrollbar-handle-interactive
| Indicates that the handle inside the scrollbar is interactive (scrollbars.dragScroll
istrue
). | |.os-scrollbar-track-interactive
| Indicates that the track inside the scrollbar is interactive (scrollbars.clickScroll
istrue
). | |.os-scrollbar-track
| The track element. This is the track of the nested handle element. Ifscrollbars.clickScroll
istrue
this is the element users can click to change the scroll offset. | |.os-scrollbar-handle
| The handle element. Ifscrollbars.dragScroll
istrue
this is the handle users can drag to change the scroll offset. | If you create your own theme, please only use the classes listed above. All other classes are modifier classes used to change visibility, alignment and pointer-events of the scrollbars. ### Gotchas Its important that the chosen theme class name in your CSS file matches the assigned theme name in the options. If the CSS class name is.my-theme
thescrollbars.theme
has to be'my-theme'
.
Please be aware of your stack.css-modules
for example will alter your class names to prevent naming collisions. Always double check if your CSS is really what you expect it to be.Plugins
Everything thats considered not core functionality or old browser compatibility is exposed via a plugin. This is done because all unused plugins are treeshaken and thus won't end up in your final bundle. OverlayScrollbars comes with the following plugins:
- ScrollbarsHidingPlugin: Is needed for old browsers which aren't supporting native scrollbar styling features. You can find the list of browsers where you need this plugin here (note that even though
iOS Safari >= 14
is marked as unsupported you only need this plugin foriOS < 7.1
). - SizeObserverPlugin: Is needed for old browsers which aren't supporting the
ResizeObserver
api. You can find the list of browsers where you need this plugin here - ClickScrollPlugin: If you want to use the option
scrollbars: { clickScroll: true }
.
Consuming Plugins
Plugins are consumed like:
import { OverlayScrollbars, ScrollbarsHidingPlugin, SizeObserverPlugin, ClickScrollPlugin } from 'overlayscrollbars'; // single plugin OverlayScrollbars.plugin(ScrollbarsHidingPlugin); // multiple plugins OverlayScrollbars.plugin([SizeObserverPlugin, ClickScrollPlugin]);
Writing Plugins
Note: For now please refer to the TypeScript definitions for a more detailed description.
You can write and publish your own Plugins. This section is a work in progress.
FAQ
How do I
get / set
thescroll position
of an element I applied OverlayScrollbars to?
If you appliedOverlayScrollbars
to thebody
element you can usewindow.scrollX
,window.scrollY
,window.scroll
,window.scrollTo
,window.scrollBy
or any other native api. If the plugin was applied to any other element you have to get theviewport
element with theinstance.elements()
function first. With this element you can useelement.scrollTop
,element.scrollLeft
,element.scroll
,element.scrollTo
,element.scrollBy
or any other native api.js const { viewport } = osInstance.elements(); const { scrollLeft, scrollTop } = viewport; // get scroll offset viewport.scrollTo({ top: 0 }); // set scroll offset
Is it possible to
limit / adjust the scrollbar handle length
?
You can adjust a scrollbars handle length by setting amin-width / min-height
andmax-width / max-height
style:css /* horizontal boundaries */ .os-scrollbar-horizontal .os-scrollbar-handle { min-width: 50px; max-width: 200px; } /* vertical boundaries */ .os-scrollbar-vertical .os-scrollbar-handle { min-height: 40px; max-height: 40px; }
You can assign the same value to both properties to force the scrollbar to be always the same size.
Setting thewidth
andheight
properties won't work since those are set by the plugin automatically.Feature comparison to
v1
- The
scroll
function is missing. Planned as aplugin
. (WIP) - Initialization to the
textarea
element isn't supported yet. Planned as aplugin
. (WIP)
Sponsors
Thanks to BrowserStack for sponsoring open source projects and letting me test OverlayScrollbars for free. Future Plans
- Provide plugin based support for missing features. (treeshakeable)
- Frequent updates in terms of bug-fixes and enhancements. (always use latest browser features)
- Improve tests. (unit & browser tests)
License
MIT