Git Product home page Git Product logo

kingsora / overlayscrollbars Goto Github PK

View Code? Open in Web Editor NEW
3.8K 3.8K 214.0 127.28 MB

A javascript scrollbar plugin that hides the native scrollbars, provides custom styleable overlay scrollbars, and preserves the native functionality and feel.

Home Page: https://kingsora.github.io/OverlayScrollbars

License: MIT License

JavaScript 8.52% TypeScript 84.55% HTML 2.17% SCSS 3.83% Vue 0.33% Svelte 0.59%
angular custom frontend javascript javascript-scrollbar-plugin library overlay overlayscrollbars react scroll scrollbar scrollbar-plugin solid solidjs svelte typescript vue

overlayscrollbars's Introduction


Downloads Version License Code Coverage Max. Bundle Size

Website   •   Examples

OverlayScrollbars

A javascript scrollbar plugin that hides the native scrollbars, provides custom styleable overlay scrollbars, and preserves the native functionality and feel.

Why?

I created this plugin because I hate ugly and space-consuming scrollbars. Similar plugins didn't meet 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 15+ and Safari 10+.
  • Fully Accessible - Native scrolling behavior is fully preserved.
  • Can run on the server (Node, Deno and Bun) - 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 required.
  • Leverage latest browser features - best performance in new browsers.
  • Flow independent - supports all values for direction, flex-direction and writing-mode.
  • Supports scroll snapping.
  • Supports all virtual scrolling libraries.
  • Supports the body element.
  • Easy and effective scrollbar styling.
  • Highly customizable.
  • TypeScript support - completely 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 and solid.

Choose your framework

In addition to the vanilla JavaScript version, you can use the official framework components & utilities:

React Vue Angular Svelte Solid

Getting started

npm & nodejs

OverlayScrollbars can be downloaded from npm or the package manager of your choice:

npm install overlayscrollbars

Once installed, it can be imported:

import 'overlayscrollbars/overlayscrollbars.css';
import { 
  OverlayScrollbars, 
  ScrollbarsHidingPlugin, 
  SizeObserverPlugin, 
  ClickScrollPlugin 
} from 'overlayscrollbars';

Note: If the path 'overlayscrollbars/overlayscrollbars.css' is not working use 'overlayscrollbars/styles/overlayscrollbars.css' as the import path for the CSS file.

You can use this Node Example as an reference / starting point.

Manual Download & Embedding

You can use OverlayScrollbars without any bundler or package manager.
Simply download one of 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, otherwise use the .es6 files.
  • For production use the javascript / stylesheet files with the .min extension.

Embed 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>

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;

You can use this Browser Example as an reference or a starting point.

The examples in this documentation use the import syntax instead of the OverlayScrollbarsGlobal object. However, both versions are equivalent.

Initialization

The initialization of OverlayScrollbars is explicit per element. Only the scrollbars of the element on which the plugin is initialized will be changed. Scrollbars of child elements will remain unchanged unless the plugin is initialized on them as well.

You can either initialize a new instance directly with an Element or with an Object where you have more control over the initialization process.

// Simple initialization with an element
const osInstance = OverlayScrollbars(document.querySelector('#myElement'), {});

Bridging initialization flickering

When you initialize OverlayScrollbars, it takes a few milliseconds to create and append all the elements to the DOM. During this time, the native scrollbars are still visible and will be switched out after the initialization is finished. This is seen as flickering.

To fix this behavior apply the data-overlayscrollbars-initialize attribute to the target element (and the html element as well when initializing a scrollbar for the body element).

<!-- 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 an in depth topic. Click here to read it.

The only required field is the target field. This is the field to which the plugin will be applied.
If you use the object initialization with only the target field, the result is equivalent to the element initialization:

// Both initializations have the same outcome

OverlayScrollbars(document.querySelector('#myElement'), {});
OverlayScrollbars({ target: document.querySelector('#myElement') }, {});

When initializing with an object you can specify how the library handles generated elements. For example, you can specify an existing element as the `viewport' element. Then the library won't generate it, but use the specified element instead:

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 create its own elements. These cases are very common when you want another library to work with OverlayScrollbars.


You can also decide to which element the scrollbars should be applied to:

OverlayScrollbars({ 
 target: document.querySelector('#target'),
 scrollbars: {
   slot: document.querySelector('#target').parentElement,
 },
}, {});

Last but not least, you can decide when to cancel the initialization:

OverlayScrollbars({ 
 target: document.querySelector('#target'),
 cancel: {
   nativeScrollbarsOverlaid: true,
   body: null,
 }
}, {});

In the above example, the initialization will be aborted if the native scrollbars are overlaid, or if your target is a body element and the plugin has determined that initializing to the body element would interfere with native functionality such as window.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 an in depth topic. Click here to read it.

The default options are:

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,
    autoHideSuspend: false,
    dragScroll: true,
    clickScroll: false,
    pointers: ['mouse', 'touch', 'pen'],
  },
};

paddingAbsolute

type default
boolean false

Indicates whether the padding for the content should be absolute.

showNativeOverlaidScrollbars

type default
boolean false

Indicates whether the native overlaid scrollbars should be visible.

update.elementEvents

type default
Array<[string, string]> | null [['img', 'load']]

An array of tuples. The first value in the tuple is an selector and the second value are event names. The plugin will update itself if any of the elements with the specified selector emits any of the specified events. The default value can be interpreted as "The plugin will update itself if any img element emits a load event."

update.debounce

type default
[number, number] | number | null [0, 33]

Note: If 0 is used for the timeout, requestAnimationFrame will be used instead of setTimeout for the debounce.

Debounces the MutationObserver 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 it is treated as the timeout and there is no max wait. With null there is no debounce. Useful to fine-tune performance.

update.attributes

type default
string[] | null null

Note: There is a base array of attributes that the MutationObserver always observes, even if this option is null.

An array of additional attributes that the MutationObserver should observe the content for.

update.ignoreMutation

type default
((mutation) => any) | null null

A function which receives a MutationRecord as an argument. If the function returns a truthy value the mutation will be ignored and the plugin won't update. Useful 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 visibility of a scrollbar if its scroll axis is able to have a scrollable overflow. (Scrollable overflow for an axis is only possible with the overflow behavior set to 'scroll' or 'visible-scroll').

scrollbars.autoHide

type default
string 'never'

Note: Valid values are: 'never', 'scroll', 'leave' and 'move'.

Dictates whether to hide visible scrollbars automatically after a certain user action.

scrollbars.autoHideDelay

type default
number 1300

The delay in milliseconds before the scrollbars are automatically hidden.

scrollbars.autoHideSuspend

type default
boolean false

Suspend the autoHide functionality until the first scroll interaction is performed.
The default value for this option is false for backwards compatibility reasons but is recommended to be true for better accessibility.

scrollbars.dragScroll

type default
boolean true

Indicates whether you can drag the scrollbar handles for scrolling.

scrollbars.clickScroll

type default
boolean | 'instant' false

Note: If set to true the ClickScrollPlugin is required.

Indicates whether you can click on the scrollbar track for scrolling.

scrollbars.pointers

type default
string[] | null ['mouse', 'touch', 'pen']

The PointerTypes the plugin should react to.

TypeScript

// The options of a OverlayScrollbars instance.
type Options = {
  // Whether the padding should be absolute.
  paddingAbsolute: boolean;
  // Whether to show the native scrollbars. Has effect only if the native scrollbars are overlaid.
  showNativeOverlaidScrollbars: boolean;
  // Customizes the automatic update behavior.
  update: {
    /**
     * The given Event(s) from the elements with the given selector(s) will trigger an update.
     * Useful for everything the MutationObserver and ResizeObserver can't detect
     * e.g.: An image's `load` event or the `transitionend` / `animationend` events.
     */
    elementEvents: Array<[elementSelector: string, eventNames: string]> | null;
    /**
     * The debounce which is used to detect content changes.
     * If a tuple is provided you can customize the `timeout` and the `maxWait` in milliseconds.
     * If a single number customizes only the `timeout`.
     *
     * If the `timeout` is `0`, a debounce still exists (and is done via `requestAnimationFrame` instead of `setTimeout`).
     */
    debounce: [timeout: number, maxWait: number] | number | null;
    /**
     * HTML attributes which will trigger an update if they're changed.
     * Basic attributes like `id`, `class`, `style` etc. are always observed and don't have to be added explicitly.
     */
    attributes: string[] | null;
    // A function which makes it possible to ignore a content mutation or null if nothing should be ignored.
    ignoreMutation: ((mutation: MutationRecord) => any) | null;
  };
  // Customizes the overflow behavior per axis.
  overflow: {
    // The overflow behavior of the horizontal (x) axis.
    x: OverflowBehavior;
    // The overflow behavior of the vertical (y) axis.
    y: OverflowBehavior;
  };
  // Customizes appearance of the scrollbars.
  scrollbars: {
    // The scrollbar's theme. The theme value will be added as `class` to all `scrollbar` elements of the instance.
    theme: string | null;
    // The scrollbar's visibility behavior.
    visibility: ScrollbarsVisibilityBehavior;
    // The scrollbar's auto hide behavior.
    autoHide: ScrollbarsAutoHideBehavior;
    // The scrollbar's auto hide delay in milliseconds.
    autoHideDelay: number;
    // Whether the scrollbar's auto hide behavior is suspended until a scroll happened.
    autoHideSuspend: boolean;
    // Whether it is possible to drag the handle of a scrollbar to scroll the viewport.
    dragScroll: boolean;
    // Whether it is possible to click the track of a scrollbar to scroll the viewport.
    clickScroll: ScrollbarsClickScrollBehavior;
    // An array of pointer types that shall be supported.
    pointers: string[] | null;
  };
};

// The overflow behavior of an axis.
type OverflowBehavior =
  // No scrolling is possible and the content is clipped.
  | 'hidden'
  // No scrolling is possible and the content isn't clipped.
  | 'visible'
  // Scrolling is possible if there is an overflow.
  | 'scroll'
  /**
   * If the other axis has no overflow the behavior is similar to `visible`.
   * If the other axis has overflow the behavior is similar to `hidden`.
   */
  | 'visible-hidden'
  /**
   * If the other axis has no overflow the behavior is similar to `visible`.
   * If the other axis has overflow the behavior is similar to `scroll`.
   */
  | 'visible-scroll';

// The scrollbars visibility behavior.
type ScrollbarsVisibilityBehavior =
  // The scrollbars are always visible.
  | 'visible'
  // The scrollbars are always hidden.
  | 'hidden'
  // The scrollbars are only visibile if there is overflow.
  | 'auto';

// The scrollbars auto hide behavior
type ScrollbarsAutoHideBehavior =
  // The scrollbars are never hidden automatically.
  | 'never'
  // The scrollbars are hidden unless the user scrolls.
  | 'scroll'
  // The scrollbars are hidden unless the pointer moves in the host element or the user scrolls.
  | 'move'
  // The scrollbars are hidden if the pointer leaves the host element or unless the user scrolls.
  | 'leave';

// The scrollbar click scroll behavior.
type ScrollbarsClickScrollBehavior = boolean | 'instant';

Events

You can initialize OverlayScrollbars with an initial set of events, which can be managed at any time with the on and off methods:

OverlayScrollbars(document.querySelector('#myElement'), {}, {
  updated(osInstance, onUpdatedArgs) {
    // ...
  }
});

Events in depth

This is an in depth topic. Click here to read it.

Note: Every event receives the instance from which it was dispatched as the first argument. Always.

initialized

arguments description
instance The instance which dispatched the event.

Dispatched after all generated elements, observers and events were appended to the DOM.

updated

arguments description
instance The instance which dispatched the event.
onUpdatedArgs An object which describes the update in detail.

Note: If an update was triggered but nothing changed, the event won't be dispatched.

Dispatched after the instance was updated.

destroyed

arguments description
instance The instance which dispatched the event.
canceled A boolean which indicates whether the initialization was canceled and thus destroyed.

Dispatched after all generated elements, observers and events were removed from the DOM.

scroll

arguments description
instance The instance which dispatched the event.
event The original event argument of the DOM event.

Dispatched by scrolling the viewport.

TypeScript

// A mapping between event names and their listener arguments.
type EventListenerArgs = {
  // Dispatched after all elements are initialized and appended.
  initialized: [instance: OverlayScrollbars];
  // Dispatched after an update.
  updated: [instance: OverlayScrollbars, onUpdatedArgs: OnUpdatedEventListenerArgs];
  // Dispatched after all elements, observers and events are destroyed.
  destroyed: [instance: OverlayScrollbars, canceled: boolean];
  // Dispatched on scroll.
  scroll: [instance: OverlayScrollbars, event: Event];
};

interface OnUpdatedEventListenerArgs {
  // Hints which describe what changed in the DOM.
  updateHints: {
    // Whether the size of the host element changed.
    sizeChanged: boolean;
    // Whether the direction of the host element changed.
    directionChanged: boolean;
    // Whether the intrinsic height behavior changed.
    heightIntrinsicChanged: boolean;
    // Whether the overflow edge (clientWidth / clientHeight) of the viewport element changed.
    overflowEdgeChanged: boolean;
    // Whether the overflow amount changed.
    overflowAmountChanged: boolean;
    // Whether the overflow style changed.
    overflowStyleChanged: boolean;
    // Whether the scroll coordinates changed.
    scrollCoordinatesChanged: boolean;
    // Whether an host mutation took place.
    hostMutation: boolean;
    // Whether an content mutation took place.
    contentMutation: boolean;
  };
  // The changed options.
  changedOptions: PartialOptions;
  // Whether the update happened with force-invalidated cache.
  force: boolean;
}

Instance

The OverlayScrollbars instance can be created by calling the OverlayScrollbars function with an element and options object.

const osInstance = OverlayScrollbars(document.body, {});

Instance Methods

This is an in depth topic. Click here to read it.

options(): Options

Get the current options of the instance.

returns description
Options The current options.

options(newOptions, pure?): Options

Sets the current options of the instance.

parameter type description
newOptions PartialOptions The new (partial) options which should be applied.
pure boolean | undefined Whether the options should be reset before the new options are added.
returns description
Options The complete new options.

on(eventListeners, pure?): Function

Adds event listeners to the instance.

parameter type description
eventListeners EventListeners An object which contains the added listeners. The fields are the event names and the listeners.
pure boolean | undefined Whether all already added event listeners should be removed before the new listeners are added.
returns description
Function A function which removes all added event listeners.

on(name, listener): Function

Adds a single event listener to the instance.

parameter type description
name string The event name.
listener Function The function invoked when the event is dispatched.
returns description
Function A function which removes the added event listener.

on(name, listeners): Function

Adds multiple event listeners to the instance.

parameter type description
name string The event name.
listeners Function[] The functions invoked when the event is dispatched.
returns description
Function A function which removes the added event listeners.

off(name, listener): void

Removes a single event listener from the instance.

parameter type description
name string The event name.
listener Function The function to be removed.

off(name, listeners): void

Removes multiple event listeners from the instance.

parameter type description
name string The event name.
listeners Function[] The functions to be removed.

update(force?): boolean

Updates the instance.

parameter type description
force boolean | undefined Whether the update should force the cache to be invalidated.
returns description
Function A boolean which indicates whether the update event was triggered through this update.

state(): State

Gets the instance's state.

returns description
State An object describing the state of the instance.

elements(): Elements

Gets the instances elements.

returns description
Elements An object describing the elements of the instance.

destroy(): void

Destroys the instance and removes all added elements.

plugin(plugin: object): object | undefined

Gets the instance modules instance of the passed plugin.

returns description
object | undefined An object which describes the plugins instance modules instance or undefined if no instance was found.

TypeScript

// A simplified version of the OverlayScrollbars TypeScript interface.
interface OverlayScrollbars {
  // Get the current options of the instance.
  options(): Options;
  // Sets the current options of the instance.
  options(newOptions: PartialOptions, pure?: boolean): Options;

  // Adds event listeners to the instance.
  on(eventListeners: EventListeners, pure?: boolean): () => void;
  // Adds a single event listener to the instance.
  on<N extends keyof EventListenerArgs>(name: N, listener: EventListener<N>): () => void;
  // Adds multiple event listeners to the instance.
  on<N extends keyof EventListenerArgs>(name: N, listener: EventListener<N>[]): () => void;

  // Removes a single event listener from the instance.
  off<N extends keyof EventListenerArgs>(name: N, listener: EventListener<N>): void;
  // Removes multiple event listeners from the instance.
  off<N extends keyof EventListenerArgs>(name: N, listener: EventListener<N>[]): void;

  // Updates the instance.
  update(force?: boolean): boolean;

  // Gets the instance's state.
  state(): State;

  // Gets the instance's elements.
  elements(): Elements;

  // Destroys the instance and removes all added elements.
  destroy(): void;

  // Gets the instance modules instance of the passed plugin.
  plugin<P extends InstancePlugin>(osPlugin: P): InferInstancePluginModuleInstance<P> | undefined;
}

// Describes a OverlayScrollbars instances state.
interface State {
  // Describes the current padding in pixels.
  padding: TRBL;
  // Whether the current padding is absolute.
  paddingAbsolute: boolean;
  // The client width (x) & height (y) of the viewport in pixels.
  overflowEdge: XY<number>;
  // The overflow amount in pixels.
  overflowAmount: XY<number>;
  // The css overflow style of the viewport.
  overflowStyle: XY<OverflowStyle>;
  // Whether the viewport has an overflow.
  hasOverflow: XY<boolean>;
  // The scroll coordinates of the viewport.
  scrollCoordinates: {
    // The start (origin) scroll coordinates for each axis.
    start: XY<number>;
    // The end scroll coordinates for each axis.
    end: XY<number>;
  };
  // Whether the direction is considered rtl.
  directionRTL: boolean;
  // Whether the instance is considered destroyed.
  destroyed: boolean;
}

// Describes the elements of a OverlayScrollbars instance.
interface Elements {
  // The element the instance was applied to.
  target: HTMLElement;
  // The host element. It's the root of all other elements.
  host: HTMLElement;
  /**
   * The element responsible for the correct padding.
   * Depending on initialization it can be the same as the viewport element.
   */
  padding: HTMLElement;
  // The element responsible of the scrolling.
  viewport: HTMLElement;
  /**
   * The element responsible for holding the actual content.
   * Depending on initialization it can be the same as the viewport element.
   */
  content: HTMLElement;
  /**
   * The element through which you can get the current `scrollLeft` or `scrollTop` offset.
   * Depending on the target element it can be the same as the viewport element.
   */
  scrollOffsetElement: HTMLElement;
  /**
   * The element through which you can add `scroll` events.
   * Depending on the target element it can be the same as the viewport element.
   */
  scrollEventElement: HTMLElement | Document;
  // The horizontal scrollbar's elements.
  scrollbarHorizontal: CloneableScrollbarElements;
  // The vertical scrollbar's elements.
  scrollbarVertical: CloneableScrollbarElements;
}

Static Object

The static OverlayScrollbars object.

OverlayScrollbars.plugin(SomePlugin);

Static Object Methods

This is an in depth topic. Click here to read it.

valid(osInstance): boolean

Checks whether the passed value is a valid and not destroyed overlayscrollbars instance

parameter type description
osInstance any The value to be checked.
returns description
boolean Whether the passed value is a valid and not destroyed overlayscrollbars instance.

env(): Environment

Gets the environment.

returns description
Environment An object describing the environment.

nonce(newNonce): void

Sets the nonce attribute for inline styles.

parameter type description
newNonce string | undefined The nonce attribute for inline styles.

plugin(plugin): object | undefined

Adds a single plugin.

parameter type description
plugin object The plugin to be added.
returns description
object | void An object describing the plugin's static module instance or void if no instance was found.

plugin(plugins): (object | void)[]

Adds multiple plugins.

parameter type description
plugins object[] The plugins to be added.
returns description
(object | void)[] An array describing the plugins static modules instances or undefined if no instance was found.

TypeScript

// The OverlayScrollbars static object.
interface OverlayScrollbarsStatic {
  // Gets the instance of the passed target or `undefined` the target has no instance.
  (target: InitializationTarget): OverlayScrollbars | undefined;
  // Initializes OverlayScrollbars to the passed target with passed options and event listeners.
  (target: InitializationTarget, options: PartialOptions, eventListeners?: EventListeners): OverlayScrollbars;

  // Checks whether the passed value is a valid and not destroyed overlayscrollbars instance.
  valid(osInstance: any): osInstance is OverlayScrollbars;

  // Gets the environment.
  env(): Environment;

  // Sets the nonce attribute for inline styles.
  nonce(newNonce: string | undefined): void;

  // Adds a single plugin.
  plugin(plugin: Plugin): InferStaticPluginModuleInstance<Plugin>
  // Adds multiple plugins.
  plugin(plugins: Plugin[]): InferStaticPluginModuleInstance<Plugin>[];
}

// Describes the OverlayScrollbars environment.
interface Environment {
  // The native scrollbars size of the browser / system.
  scrollbarsSize: XY<number>;
  // Whether the native scrollbars are overlaid.
  scrollbarsOverlaid: XY<boolean>;
  // Whether the browser supports native scrollbar hiding.
  scrollbarsHiding: boolean;
  // Whether the browser supports the ScrollTimeline API.
  scrollTimeline: boolean;
  // The default Initialization to use if nothing else is specified.
  staticDefaultInitialization: Initialization;
  // The default Options to use if nothing else is specified.
  staticDefaultOptions: Options;

  // Returns the current default Initialization.
  getDefaultInitialization(): Initialization;
  // Returns the current default Options.
  getDefaultOptions(): Options;

  /**
   * Sets a new default Initialization.
   * If the new default Initialization is partially filled, its deeply merged with the current default Initialization.
   * @param newDefaultInitialization The new default Initialization.
   * @returns The current default Initialization.
   */
  setDefaultInitialization(newDefaultInitialization: PartialInitialization): Initialization;
  /**
   * Sets new default Options.
   * If the new default Options are partially filled, they're deeply merged with the current default Options.
   * @param newDefaultOptions The new default Options.
   * @returns The current default options.
   */
  setDefaultOptions(newDefaultOptions: PartialOptions): Options;
}

Styling

OverlayScrollbars comes with two themes called os-theme-dark and os-theme-light. You can use the scrollbars.theme option to change the theme.

Custom themes can be done in several ways. The easiest and fastest way is to use the predefined set of CSS Custom Properties aka CSS variables. If that's not enough, you can add custom class names or add custom styling to the existing class names.

Styling in depth

This is an in depth topic. Click here to read it.

CSS Custom properties

OverlayScrollbars provides a set of CSS Custom Properties which makes scrollbar styling easy and fast:

.os-scrollbar {
  // The size of the scrollbar
  --os-size: 0;
  // The axis-perpendicular 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-perpendicular size of the scrollbar handle (horizontal: height, vertical: width)
  --os-handle-perpendicular-size: 100%;
  // The :hover axis-perpendicular size of the scrollbar handle (horizontal: height, vertical: width)
  --os-handle-perpendicular-size-hover: 100%;
  // The :active axis-perpendicular 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 change the properties for both scrollbars at once, or for each scrollbar axis. In the example below, I've chosen os-theme-custom as the theme name:

// 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 the scrollbars.theme option:

OverlayScrollbars(document.body, {
  scrollbars: {
    theme: 'os-theme-custom'
  }
});

Since scrollbar styles are usually simple, this set of options should be enough to get the styling you want. If 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:

<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 a RTL 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 is not false).
.os-scrollbar-track-interactive Indicates that the track inside the scrollbar is interactive (scrollbars.clickScroll is not false).
.os-scrollbar-track The track element. This is the track of the nested handle element. If scrollbars.clickScroll is not false this is the element users can click to change the scroll offset.
.os-scrollbar-handle The handle element. If scrollbars.dragScroll is not false 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

It is 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, the scrollbars.theme must be 'my-theme'.

Please be aware of your stack. For example, css-modules will change your class names to avoid naming collisions. Always check that your CSS is what you expect it to be.

Plugins

Anything that is not considered core functionality or old browser compatibility is exposed via a plugin. This is done because all unused plugins are omitted during treeshaking and won't end up in your final bundle. OverlayScrollbars ships with the following plugins:

Consuming Plugins

Plugins are consumed like:

import { 
  OverlayScrollbars, 
  ScrollbarsHidingPlugin, 
  SizeObserverPlugin, 
  ClickScrollPlugin 
} from 'overlayscrollbars';

// Single plugin
OverlayScrollbars.plugin(ScrollbarsHidingPlugin);

// Multiple plugins
OverlayScrollbars.plugin([SizeObserverPlugin, ClickScrollPlugin]);

Plugins in depth

This is an in depth topic. Click here to read it.

Plugins are plain objects with a single field, the name of the field is the name of the plugin. This name is the plugin's identifier and must be unique across all plugins. In case multiple plugins have the same name, the last added plugin overwrites the plugin added previously under the same name.

Plugin Modules

A Plugin module is the constructor of a plugin module's instance. There are two kinds of plugin modules: static and instance. A single plugin must have one or more modules. A plugin module can return an instance, but doesn't have to.

Static Plugin Module

The static plugin module is invoked when the plugin is added with the OverlayScrollbars.plugin function.

Example plugin with a static module:

const staticPlugin = {
  // Plugin has the name `examplePlugin`.
  examplePlugin: {
    // The `static` function describes a static module and returns the module instance or void / undefined if no instance is needed.
    // The `osStatic` parameter is the global `OverlayScrollbars` object.
    static: (osStatic) => {
      let count = 0;
      const staticPluginModuleInstance = {
        getCount: () => count,
        increment: () => { count++ },
      }
      return staticPluginModuleInstance;
    }
  }
}

When the plugin is added with the OverlayScrollbars.plugin function, the static module instance is returned:

const staticModuleInstance = OverlayScrollbars.plugin(staticPlugin); // Plugins static module is invoked
staticModuleInstance.count; // 0
staticModuleInstance.increment();
staticModuleInstance.count; // 1

Instance Plugin Module

The instance plugin module is invoked when a new OverlayScrollbars instance is created but before the initialized event is dispatched.

Example plugin with a instance module:

const instancePlugin = {
  // Plugin has the name `examplePlugin`.
  examplePlugin: {
    // Instance function describes na instance module and returns the module instance or void / undefined if no instance is needed.
    // The `osInstance` parameter is the OverlayScrollbar instance the plugin is bound to.
    // The `event` parameter is a function which adds events to the instance which can't be removed from outside the plugin.
    // The `osStatic` parameter is the global OverlayScrollbar object.
    instance: (osInstance, event, osStatic) => {
      let count = 0;

      const instancePluginModuleInstance = {
        getCount: () => count,
        increment: () => { count++ },
      }

      // Event which fires when the instance was initialized.
      event('initialized', () => {
        console.log("instance initialized");
      });

      // Event which fires when the viewport was scrolled.
      const removeScrollEvent = event('scroll', () => {
        console.log("viewport scrolled");
        removeScrollEvent(); // Removes the event after the first scroll.
      });
      
      return instancePluginModuleInstance;
    }
  }
}

When the plugin is added with the OverlayScrollbars.plugin function, all OverlayScrollbar instances will automatically add the plugin from that point on. Previously created instances will not have the plugin. The instance module instance is returned with the osInstance.plugin function:

OverlayScrollbars.plugin(instancePlugin); // Plugin is added

const osInstance = OverlayScrollbars(document.body, {}); // Plugin's instance module is invoked
const instancePluginInstance = osInstance.plugin(instancePlugin);

instancePluginInstance.count; // 0
instancePluginInstance.increment();
instancePluginInstance.count; // 1

TypeScript

// Describes a OverlayScrollbar plugin.
type Plugin<
  // The name of the plugin.
  Name extends string = string,
  // The module instance type of the static module.
  S extends PluginModuleInstance | void = PluginModuleInstance | void, 
  // The module instance type of the instance module.
  I extends PluginModuleInstance | void = PluginModuleInstance | void 
> = {
  [pluginName in Name]: PluginModule<S, I>;
};

// Describes a OverlayScrollbar plugin which has only a static module.
type StaticPlugin<
  Name extends string = string,
  T extends PluginModuleInstance = PluginModuleInstance
> = Plugin<Name, T, void>;

// Describes a OverlayScrollbar plugin which has only a instance module.
type InstancePlugin<
  Name extends string = string,
  T extends PluginModuleInstance = PluginModuleInstance
> = Plugin<Name, void, T>;

// Infers the type of the static module's instance of the passed plugin.
type InferStaticPluginModuleInstance<T extends StaticPlugin>;

// Infers the type of the instance modules instance of the passed plugin.
type InferInstancePluginModuleInstance<T extends InstancePlugin>;

FAQ

How do I get / set the scroll position of an element I applied OverlayScrollbars to?

If you applied OverlayScrollbars to the body element you can use window.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 the viewport element with the instance.elements() function first. With this element you can use element.scrollTop, element.scrollLeft, element.scroll, element.scrollTo, element.scrollBy or any other native api.

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 scrollbar's handle length by setting a min-width / min-height and max-width / max-height style:

/* 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 the width and height properties won't work since those are set by the plugin automatically.

Feature comparison to v1

  • The scroll function is missing. Planned as a plugin. (WIP)
  • Initialization to the textarea element isn't supported yet. Planned as a plugin. (WIP)

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)

Used by

Sponsors

Thanks to BrowserStack for sponsoring open source projects and letting me test OverlayScrollbars for free.

License

MIT

overlayscrollbars's People

Contributors

4s1ght avatar addisonelliott avatar alex-sokolov avatar andrii-vovk avatar arturovt avatar dependabot[bot] avatar gandalfthegreydev avatar kant avatar kingsora avatar mrg0lden avatar swoorpious avatar tryggvigy avatar zhephyr54 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

overlayscrollbars's Issues

Issue with Overlays on an ul.dropdown-menu element

Hi there:

I found a new issue when using the OverlayScrollbars on a Materialize dropdown-menu element.

I have this part of the code on my Initialization method (I use jquery)

$(document).ready(function(){
    $('.dropdown-menu').overlayScrollbars({ 
       className: "os-theme-dark",
        scrollbars : {
        visibility  : "auto",
        autoHide  : "move",
        touchSupport  : true
      },
    }); 

Then I construct my dropdown-menu dynamically and here are some CSS snippets from the materialize.css file

.open>.dropdown-menu {
	display: block;
}
.open>a {
	outline: 0;
}

.dropdown-menu {
	position: absolute;
	top: 100%;
	left: 0;
	z-index: 1000;
	display: none;
	float: left;
	min-width: 160px;
	padding: 30px 0;
	margin: 2px 0 0;
	text-align: left;
	list-style: none;
	background-color: #fff;
	-webkit-background-clip: padding-box;
	background-clip: padding-box;
	border: 1px solid #ccc;
	border: 1px solid rgba(0,0,0,.15);
	border-radius: 4px;
	-webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
	box-shadow: 0 6px 12px rgba(0,0,0,.175);

	li > a {
		display: block;
		padding: 5px 40px;
		clear: both;
		font-weight: 400;
		line-height: 1.42857143;
		color: #333;
		white-space: nowrap;

		&:hover {
			background-color: #0064b3;
			color: #fff;
			text-decoration: none;
		}
	}
}

.dropdown .dropdown-menu li > a {
  &:hover {
    color: #FFBA20;
  }
}

So here it is how my dropdown menu element looks like without OverlaysScrollbar on Mac OS X
no overlays enabled mac os x

So here it is how my dropdown menu element looks like without OverlaysScrollbar on Windows (look at the scrolling bar)
no overlays enabled windows

And this is how my dropdown menu element looks like when using OverlaysScrollbar. It gets all messed up.
with overlays enabled

@KingSora, my question is: How can I fix this behavior to respect the CSS styling on my materialize CSS class?

"main" field in package.json should point to unminifie code.

Currently the main field in package.json points to js/OverlayScrollbars.min.js. I think it will be better if it points to js/OverlayScrollbars.js. it will have the following benefits:

  • During dev, one needs an unminified view of the libs, so that one may debug deeper.
  • Most apps, will have their own minification/packaging. Unminified code plugs in better with that
    workflow, including better compression ratios.

Apply on Materialize sideNav

Works fine when I use $('body').overlayScrollbars({ }); or $('div').overlayScrollbars({ });

but nothing happens when i do this $('#some_div_id').overlayScrollbars({ }); or this $('.some_div_class').overlayScrollbars({ });

Issue with a floating element on body

Hi @KingSora:

Found new bug on this implementation.. After adding the code you sent me, there was one element I couldn't see on the page after installing OverlayScrollbars. It is a floating element which is attached to the body after the construction of body.

Here is a screenshot of the Quick Notes window floating in the bottom right part of the site BEFORE adding OverlayScrollbars:
39738969-f7b59e10-5253-11e8-9f10-2deaca46608a

Now, there is a screenshot of the same floating window AFTER OverlayScrollbars:
39738977-fae2801c-5253-11e8-8ea0-86c3dfef1805

Here is how I declared the Quick Notes div on my initial javascript OverlayScrollbars file. It doesn't show when the page loads the first time but the quick notes DIV is shown after clicking on the sideNav element:

var osBodyInstance = $('body').overlayScrollbars({ }).overlayScrollbars();
var quicknotesElms = $('body > #quick-notes-widget');
var osContentElmQN = $(osBodyInstance.getElements().content);
osContentElmQN.append(quicknotesElms);
$(".settings-nav-btn").sideNav({
  menuWidth: 300,
  edge: 'right',
  closeOnClick: true,
  draggable: true,
  onOpen: function() {
    var sidenavElms = $('body > .sidenav-overlay, body > #sidenav-overlay, body > .drag-target');
    var osContentElm = $(osBodyInstance.getElements().content);
    if (sidenavElms.length > 0 && osContentElm.length > 0) {
      osContentElm.append(sidenavElms);
      osContentElm.append(sidenavElmsQN);
    }
  }
});

And this is the JS that attaches the quick notes to the main body of the page.

updateQuickNoteCounter = (inc) ->
  countEl = $('#quick-notes-count')
  countEl.html(parseInt(countEl.html()) + inc) # update counter in header

$ ->
  $(document).on 'click', '.quick-notes-header', ->
    $(this).parent().toggleClass('expanded')

  $(document).bind 'quick-notes:create', (e, html) ->
    $('.quick-notes-body ul').prepend(html)
    $('.quick-notes-body textarea').val('').trigger('mouseover'); # reset form, trigger mouseover need to reset counter
    updateQuickNoteCounter(1)

  $(document).bind 'quick-notes:remove', (e, id) ->
    $('#' + id).remove()
    updateQuickNoteCounter(-1)

Any idea how Can I fix it to support this Floating element when the page loads the first time?

Scrollbar position

I have a layout that requires the scrollbar to be positioned on the outside of the scrollable content. If I add right: -4.24vw; or transform: translateX(4.24vw); the overflow: hidden !important class on the .os-host-overflow element cuts off the scrollbar. I manually overwrote this CSS style and it looks ok in chrome 64 (Mac OSX), but I haven't tested in other browsers yet.

I found a link to this library on reddit and decided to give it a try. So far it handles scrolling noticeably better than the malihu custom scrollbar plugin. The malihu plugin would occasionally lurch the scroll position while scrolling.

Usage with Flexbox and VirtualList

I have a case that works fine in Firefox, but not in Chrome. Below I have tried to make a little sample of the case -- the real case it is taken from is a fixed-position navigation tree on the left side of a page. Clicking on a node in the tree expands children. When the tree gets too tall, a scrollbar should appear. This works fine in Firefox but not in Chrome.

Example HTML:

<div style="display:flex;flex-flow:column nowrap;width:200px;position:fixed;z-index:1;top:300px;left:0;background:darkred;color:white;height:calc(100vh - 300px);">
    <div style="flex-shrink:0;padding:20px;">
        Some Stuff
    </div>
    <div id="testScroll" style="flex-grow:1;margin:10px 0 30px 0;border-top:1px solid white;border-bottom:1px solid white;">
        <div id="dynamicContent">
            <div>FIRST THING</div>
            <div>A thing</div>
            <div id="interestingThing">Click this thing</div>
            <div id="extraStuff" style="display:none;">
                <div style="height:700px">Another Tall Thing</div>
            </div>
            <div style="height:500px;">A Tall Thing</div>
            <div>LAST THING</div>
        </div>
    </div>
</div>

Example js:

const scrollbar = OverlayScrollbars(document.getElementById("testScroll"), { className: "os-theme-light" });

document.getElementById("interestingThing").addEventListener("click", e => {
    let stuff = document.getElementById("extraStuff");
    if (getComputedStyle(stuff).display === "block")
        stuff.style.display = "none";
    else
        stuff.style.display = "block";
});

I have reproduced some of the styles from my real example in case it's something specific causing the issue. To see the issue, make your browser window tall enough that you can see "LAST THING" without needing a scrollbar. Then click on "Click this thing" to show "Another Tall Thing". A scrollbar should appear so you can scroll down to see "LAST THING". This works in FF as expected, but not in Chrome.

Any help would be appreciated -- so far I'm really liking this scrollbar script.

Why OverlayScrollbars.js is so heavy? (53kb minified)

Hello @KingSora, and thanks for your work!
I run a size-limit --why, because I found that my bundle size was heavy,

image

As you could see, OverlayScrollbars is one of the two heaviest libraries in my bundle, next to vuejs..!
vue.js : 278kb normal, 102kb minified
OverlayScrollbars.js : 294kb normal, 53kb minified

Any plans to reduce that size?

Thanks,

Remember scroll position after reload or page switch

We use the OverlayScrollbars on a body element which works great.

The only problem is when the user scrolls down the page and reloads the page the scrollbar always gets initialized to top most position. That means with other words, he does not get back to the former position on the page.

The standard scrollbar seems to consider that. We initialize OverlayScrollbars in the document.ready() function. Do we oversee something? Or is it not possible to "remember" the position of the scrollbar?

Many thanks for a feedback.

Add module support

This is a great library - much better than the other's I have seen.

Any possibility of supporting a module architecture (ES6 for example)?

import OverlayScrollbars from 'overlayscrollbars';

let scrollbar = OverlayScrollbars(ref, options);

Using OverlayScrollbars with Materialize

Hi:

I'm creating a new site using Materialize.css and there is one function I'm using, .sideNav(), (https://materializecss.com/sidenav.html) which allows creating a slideout menu. The issue here is when I include the OverlaysScrollbars css and js files on my code, I'm not able to access the elements inside of the menu for some reason. The result of including Overlays code is an sidenav-overlay class that covers all the screen and I can't click on each element on the menu.

Here is a small snippet of my code along with Overlays Scrollbars initialization.

$(document).ready(function(){
$('.button-collapse').sideNav();
$('.parallax').parallax();
$('.collapsible').collapsible();
// NOTE: m_slider = materialize slider, we rename it because it conflicted with jquery UI slider
$('.slider').m_slider();
$('.dropdown-button').dropdown({
inDuration: 300,
outDuration: 225,
constrainWidth: false,
hover: false,
gutter: 0,
belowOrigin: true,
alignment: 'left',
closeOnClick: true
}
);
$('.settings-nav-btn').sideNav({
menuWidth: 300,
edge: 'right',
closeOnClick: true,
draggable: true,
});
$('body').overlayScrollbars({
className: "os-theme-dark",
scrollbars : {
visibility : "auto",
autoHide : "move",
touchSupport : true
},
});
});

Uncaught TypeError: Cannot read property 'querySelectorAll' of undefined

When I try to use it in my React app, I get this error:
image

I made
import {OverlayScrollbars} from 'overlayscrollbars/js/OverlayScrollbars';
and after mounting all page try this: OverlayScrollbars(document.querySelectorAll('body'), { });
body element is available in this moment and logging into console:
image

Not working as expected

I just tried to implement this script in my existing structure.

There's a div container, that is dynamically being filled with contents. It has a max-height of 500px:

<div class="container">
	<div class="innerDivA" style="display: block;">
		<!-- foo -->
	</div>
		
	<div class="innerDivB" style="display: block;">
		<!-- foo -->
	</div>
</div>

As soon as i execute your script on the container div, it becomes this:

<div class="container os-host os-theme-dark os-host-resize-disabled os-host-scrollbar-horizontal-hidden os-host-scrollbar-vertical-hidden os-host-transition">
	<div class="os-resize-observer-host">
		<div class="os-resize-observer observed" style="left: 0px; right: auto;">
		</div>
	</div>
	<div class="os-size-auto-observer" style="height: calc(100% + 1px); float: left;">
		<div class="os-resize-observer observed">
		</div>
	</div>
	<div class="os-content-glue" style="width: 252px; margin: 0px -5px 0px 0px; height: 501px;">
	</div>
	<div class="os-padding">
		<div class="os-viewport" style="right: 0px; bottom: 0px;">
			<div class="os-content-arrange">
			</div>
			<div class="os-content" style="padding: 0px 5px 0px 0px; height: auto; width: 100%;">
				<div class="innerDivA" style="display: block;">
					<!-- foo -->
				</div>
				<div class="innerDivB" style="display: block;">
					<!-- foo -->
				</div>
			</div>
		</div>
	</div>
	<div class="os-scrollbar os-scrollbar-horizontal os-scrollbar-unusable">
		<div class="os-scrollbar-track os-scrollbar-track-off">
			<div class="os-scrollbar-handle" style="width: 100%; transform: translate(0px, 0px);">
			</div>
		</div>
	</div>
	<div class="os-scrollbar os-scrollbar-vertical os-scrollbar-unusable">
		<div class="os-scrollbar-track os-scrollbar-track-off">
			<div class="os-scrollbar-handle" style="height: 100%; transform: translate(0px, 0px);">
			</div>
		</div>
	</div>
	<div class="os-scrollbar-corner">
	</div>
</div>

This results in an empty container directly before the element with a height of 501px (or whatever is being calculated). The scrollbar remains the system default one and i have two scrollbars now (the one from the element itself due to overflow-y: auto; and another one, that belongs to your plugin):

image

I just checked your recent issues and found #4 where you also posted a demo (https://jsfiddle.net/rq4xq5jf/1/). There, it also seems not to work as it should and i guess, it's the same problem.

Cannot create property 'guid' on number ...

I'm getting the following error when trying to use any kind of scroll command:
instance.scroll(100);

Uncaught TypeError: Cannot create property 'guid' on number '100'
at Object.add (jquery.min.js:2)
at HTMLBodyElement. (jquery.min.js:2)
at Function.each (jquery.min.js:2)
at w.fn.init.each (jquery.min.js:2)
at De (jquery.min.js:2)
at w.fn.init.on (jquery.min.js:2)
at w.fn.init.w.fn.(anonymous function) [as scroll] (https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js:2:85766)
at :1:11

Any help is appreciated :)

Thanks,
Ben

[Todos & Plans] v1.4.5 and beyond

This is sort of a roadmap for version 1.4.5 and beyond:

Code imporvements:

  • vanilla version fix helper init bug where a empty array is returned as first element (line 530)
  • all versions fix a bug where async methods are executed even if the instance is destroyed
  • all versions in InternetExplorer sometimes the plugin won't initialize in a iFrame
  • all versions extended iFrame support: for example the method getState() will provide information whether the instance is in a iframe.
  • all versions refresh viewportSize after "correct measuring" in update method.

General enhancements:

  • make a benchmark between vanilla and jQuery version
  • make a benchmark / feature comparison between OverlayScrollbars and similar plugins
  • extend the documentation page with a article about how to use OverlayScrollbars in a flexbox layout
  • extend the demo page with a iFrame demo

Features:

  • implement a extension system to make it possible to implement own / specific features more easy (v1.5.0)
  • find a way to use this plugin more easy with tables without third party plugins (via extensions maybe?)

If you have any suggestions or ideas, feel free to post them!

About new releases.

I like the way you support us, and how you're fixing the bugs, but it is annoying how new versions are released. For example, version 1.4.3 to 1.4.4, jQuery Release... What changed? Nothing, but new version was released. That confusing a lot... May be you should separate this versions, also jquery one and vanilla?

What is the point of corner evement?

I've noticed small thing, that following div "os-scrollbar-corner" is added on all elements like span, div, etc. What is the point of this one, when corner is probably only needed on textarea fields?

Place of scroll track

Is it possible to put the scroll bars on the outside of the container? Quite often I require the scroll content to be laid out exactly as is but nicely scrollable, but with OverlayScrollbars, it often places the scrollbar over the content.

Can't set defaults using jQuery

OverlayScrollbars.defaultOptions({...}) and $.fn.overlayScrollbars().defaultOptions({...}) throws an error, meaning you can't access defaultOptions() method.

Found a workaround though... But I'm not sure this is intended behavior.

$.fn.overlayScrollbars();
OverlayScrollbars.defaultOptions({...})

after calling $.fn.overlayScrollbars() everything works... Weird...

How do I get the scroll position?

I can't seem to get the scroll position of the element.
I've tried it like this:
pageContentScroll);`

Maybe I'm overlooking something or misunderstanding your documentation, but it's not working for me. Could you please help me get this right?

Dynamic filled content?

Will this one work well on dynamic filled content?
Let's say on small chatbox on top of jquery?

Does scroll() function work correctly?

Hi.
I used your OverlayScrollbars jquery plugin to show customized scrollbar.
I want to scroll top or bottom window automatically when user click a button.
So I tired this.

var instance;
        $(function() {
            //The passed argument has to be at least a empty object or a object with your desired options
            instance = $('body').overlayScrollbars({
                callbacks: {
                    onScroll: function(eventArgs) { 
                        var scroll = eventArgs.srcElement.scrollTop;
                        if (scroll >= 1) {
                            $(".boxfit-navbar").addClass("fixed");
                        } else {
                            $(".boxfit-navbar").removeClass("fixed");
                        }                    
                    }
                }
             });

             $('#down-to-bottom-button').click(function() {
                 instance.scroll(0, 250);
             });

But it doesn't work.
What can I do now?

Bootsrap Modal is not working

Hi, thank you for your awesome plugin. I like it but there is a small bug whois is the bootstrap modal is not working properly after installing your plugin. When I click the modal button it's open but never close and on the top of the modal, there is a black mask. Hope I will get a solution soon.

Thank you

Wrapping around instead of replacing?

I have a suggestion of adding how plugin structure will be added. I will provide small example, so you can better understand what i mean.

Let's assume following HTML structure is given:

<div id="chat">
  <div id="messages">
    ... list of messages ...
  </div>
  <div id="input">
    ... input field ...
  </div>
</div>

We want to make our messages scrollable and input element should be static/not scrollable. We do:
var messages= $('#messages').overlayScrollbars({ }).overlayScrollbars();

Seems good so far, but, our element #messages is replaced with container of overlayScrollbar, and now we can not fill/add our chat messages to #messages, beucase it is broken now. The only possibility in this case is to add some middleware container which will make it scrollable, for example like this:

<div id="chat">
  <div id="scroll">
    <div id="messages">
      ... list of messages ...
    </div>
  </div>
  <div id="input">
    ... input field ...
  </div>
</div>

With such initialization:
var messages= $('#scroll').overlayScrollbars({ }).overlayScrollbars();

In this case we will be able to add all our messages directly to #messages.

My suggestion is actually not to replace the selected element with overlayScrollbars containers, but by wrapping around it, so we will not have to add some other containers to make it work.

Hope you understand what i mean :)

IE11 + Vue sometimes gets error "TypeError: Permission denied"

I couldn't reproduce this plug on a simple examples
When using complicated VUE app I get a lot of "TypeError: Permission denied" on line 909
if (el.addEventListener) {
And the OverlayScrollbars won't replace the element's scrollbars.

When I wrap this with Try & Catch the error is gone and OverlayScrollbars is working.
try {el.addEventListener if (el.addEventListener) { for (i = 0; i < eventName.length; i++) el.addEventListener(eventName[i], handler); } else if(el.detachEvent) { for (i = 0; i < eventName.length; i++) el.attachEvent('on' + eventName[i], handler); } } catch (e) { // console.log(e); }

Scroll to a specific position with a single click

Hello,

  1. It is possible to scroll on track with one click (tap on mobile) where cursor is?
    It will make the scrollbar more useful to scroll to a specific position in the page without pulling the scrollbar, the current behavior is bad and is not precise. Saw here
  2. It is possible to set a page transition speed value while scrolling after click? Similar here
    Will be nice instead of direct jump.

Something like this:
scrollbar

Error when loading facebook SDK

hi, i'm back
I'm sorry about that but when i load the facebook javascript SDK i get errors from OverlayScrollbar.js.

Uncaught DOMException: Blocked a frame with origin "http://www.cc-paimpol-goelo.com" from accessing a cross-origin frame. at http://www.cc-paimpol-goelo.com/maquettes_cyber/gp3a-2/wp-content/themes/gp3a/js/OverlayScrollbars.min.js:14:10504 at x.each (http://www.cc-paimpol-goelo.com/maquettes_cyber/gp3a-2/wp-content/themes/gp3a/js/OverlayScrollbars.min.js:14:8725) at v.each (http://www.cc-paimpol-goelo.com/maquettes_cyber/gp3a-2/wp-content/themes/gp3a/js/OverlayScrollbars.min.js:14:8853) at v.on (http://www.cc-paimpol-goelo.com/maquettes_cyber/gp3a-2/wp-content/themes/gp3a/js/OverlayScrollbars.min.js:14:10476) at http://www.cc-paimpol-goelo.com/maquettes_cyber/gp3a-2/wp-content/themes/gp3a/js/OverlayScrollbars.min.js:14:16359 at new c (http://www.cc-paimpol-goelo.com/maquettes_cyber/gp3a-2/wp-content/themes/gp3a/js/OverlayScrollbars.min.js:14:16828) at l (http://www.cc-paimpol-goelo.com/maquettes_cyber/gp3a-2/wp-content/themes/gp3a/js/OverlayScrollbars.min.js:14:13656) at e.(anonymous function) (http://www.cc-paimpol-goelo.com/maquettes_cyber/gp3a-2/wp-content/themes/gp3a/js/OverlayScrollbars.min.js:14:53145) at HTMLDocument.<anonymous> (http://www.cc-paimpol-goelo.com/maquettes_cyber/gp3a-2/wp-content/themes/gp3a/js/init-accueil.js:96:29) at l (https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js?ver=3.3.1:2:29375)

error in my script init-accueil at line 96 correspond to the creation of my scrollbar instance.

If i don't load facebook sdk all is alwright.

Last thing, error occurs in chrome, IE but not in Firefox (i don't remember if i add a security exception..)

Thx for help,

Fred, Brittany - France.

Scroll bar does not update itself accurately

I'm developing a product with a feed/wall of posts and i'm loading the images with lazy loading.
The scroll bar is getting "crazy" every time an image is loaded, it goes up and down and sometimes i can't reach the end of the feed or in some cases i have a gap between the end of the bar to the actual end of the feed.

What is the problem and what can i do?

Try to make a simple feed with lazyload images async and you will see.

onScroll callback

Hi, and congrats for your work,

I have a warning when i try to use the onScroll callback : here's what i can read in firefox console :

The following options are discarded due to invalidity: { "onScroll": "function" } (OverlayScrollbars.min.js:14:31423)

I really nead to listen to this callback, please help.

Fred, Brittany - France

Capability of scrolling over a fixed element

I have a fixed footer that is hidden behind content wrapper and gets revealed when the scroll hits the bottom of the page. OverlayScrollbars is working nice in general, but mousewheel up over this fixed footer does not trigger scroll change.

This can also be tested on the demo page, mouse-scrolling over the fixed header does not move the content scroll, while native scroll would do so.

Note. Not sure this is rather a feature request than an issue, please tell me if I am misaddressing.

Error if initialize on an empty element

If you try to initialize a scrollbar on an empty element, it gives this error:

TypeError: Argument 1 of Node.appendChild does not implement interface Node.
overlayscrollbars.js:1142:25

I can reproduce this with e.g.

<div id="test"></div>

OverlayScrollbars(document.getElementById("test"), { });

Sometimes I may wish to do this if I haven't filled that div with content yet, e.g. a dynamically loaded list. For now I have deferred initializing the scrollbar until after the first time the container has at least one thing in it, but would be nice to not have to do that.

Slow performance due to animations

So, everything works great up until I have about 10 or more elements on page that are initialized by OverlayScrollbar instance.

I have sections across the site and when I get to about 10 or more the OverlayScrollbar slows down drawing of elements and the wait is about 10-20 seconds before elements shows up. It's like CPU gets overloaded until it executes and initializes all elements and then it starts working. Something is going on under the hood with a bunch of divs using the OverlayScrollbar.

This is how I initialize:

$('.overlayScroll').overlayScrollbars({ className : "os-theme-dark", resize : "none", sizeAutoCapable : true, paddingAbsolute : true, overflowBehavior: { x: "hidden" }, });
Each area I want to make scrollable has this format:

<div class="section-content overlayScroll"> <div class="overlayScrollContent"> <div class="inner-title">Some title</div> <div class="inner-content">Some content text</div> </div> </div>

Everything works ok up to maybe 8-10 or so elements but then suddenly everything slows down to a crawl. One thing to note is that I'm using flexbox for most elements.

Scrollbar jumps after Dragging manually with mouse

OverlayScrollbar works as expected until you use the mouse to drag the scrollbar, after which it starts jumping on each mouse move.

Version: 1.4.1 (1.4.4 does not work with AMD)
Options:

 {
          scrollbars: {
                autoHide: 'leave',
                autoHideDelay: 300
          }
}

Browser: Chrome, Firefox

I use the Plain Javascript version. Here is a demo of the problem:

scrollbar

OverlayScrollbars.js:5102 Uncaught TypeError: Right-hand side of 'instanceof' is not an object

Hi,
I got this error when use scroll method, OverlayScrollbars without jQuery.

var possibleElementIsJQuery = possibleElement instanceof helper || possibleElement instanceof window.jQuery;

OverlayScrollbars.js:5102 Uncaught TypeError: Right-hand side of 'instanceof' is not an object
at window.(anonymous function).OverlayScrollbarsInstance._base.scroll (webpack:///./node_modules/overlayscrollbars/js/OverlayScrollbars.js?:5102:104)

autoHide mousemove

Library (and documentation) looks really great!

I would like an extra option for autoHide / show. If you have it on 'scroll' for example, I would like to also be able to see the scrollbar when I move my mouse on the page, and also hide it after X miliseconds.

P.s. I made an issue on cdnjs to get it 'hosted' over there:
cdnjs/cdnjs#12562

TypeScript definition file [v1.4.5]

I created one for my own purposes, which may be useful to you:

type ResizeBehavior = "none" | "both" | "horizontal" | "vertical" | "n" | "b" | "h"|  "v";

type OverflowBehavior = "hidden" | "scroll" | "visible-hidden" | "visible-scroll" |  "h" | "s" | "v-h" | "v-s";

type VisibilityBehavior = "visible" | "hidden" | "auto" | "v" | "h" | "a";

type AutoHideBehavior = "never" | "scroll" | "leave" | "move" | "n" | "s" | "l" | "m";

type EventCallback = function (this: OverlayScrollbars): void;

interface OverlayScrollbarsOptions {
	className?            : string | null,
	resize?               : ResizeBehavior,
	sizeAutoCapable?      : boolean,
	clipAlways?           : boolean,
	normalizeRTL?         : boolean,
	paddingAbsolute?      : boolean,
	autoUpdate?           : boolean | null,
	autoUpdateInterval?   : number,
	nativeScrollbarsOverlaid? : {
		showNativeScrollbars?  : boolean,
		initialize?            : boolean
	},
	overflowBehavior? : {
		x? : OverflowBehavior,
		y? : OverflowBehavior
	},
	scrollbars? : {
		visibility?       : VisibilityBehavior,
		autoHide?         : AutoHideBehavior,
		autoHideDelay?    : number,
		dragScrolling?    : boolean,
		clickScrolling?   : boolean,
		touchSupport?     : boolean
	},
	textarea? : {
		dynWidth?  : boolean,
		dynHeight? : boolean
	},
	callbacks? : {
		onInitialized?               : EventCallback | null,
		onInitializationWithdrawn?   : EventCallback | null,
		onDestroyed?                 : EventCallback | null,
		onScrollStart?               : EventCallback | null,
		onScroll?                    : EventCallback | null,
		onScrollStop?                : EventCallback | null,
		onOverflowChanged?           : EventCallback | null,
		onOverflowAmountChanged?     : EventCallback | null,
		onDirectionChanged?          : EventCallback | null,
		onContentSizeChanged?        : EventCallback | null,
		onHostSizeChanged?           : EventCallback | null,
		onUpdated?                   : EventCallback | null
	}
}

interface ScrollInfo {
	x : {
		position          : number,
		ratio             : number,
		max               : number,
		handleOffset      : number,
		handleLength      : number,
		handleLengthRatio : number,
		trackLength       : number,
		isRTL             : boolean
		isRTLNormalized   : boolean
	},
	y : {
		position          : number,
		ratio             : number,
		max               : number,
		handleOffset      : number,
		handleLength      : number,
		handleLengthRatio : number,
		trackLength       : number
	}
}

interface Elements {
	target   : HTMLElement,
	host     : HTMLElement,
	padding  : HTMLElement,
	viewport : HTMLElement,
	content  : HTMLElement,
	scrollbarHorizontal : {
		scrollbar : HTMLElement,
		track     : HTMLElement,
		handle    : HTMLElement
	},
	scrollbarVertical : {
		scrollbar : HTMLElement,
		track     : HTMLElement,
		handle    : HTMLElement
	},
	scrollbarCorner : HTMLElement
}

interface State {
	sleeping      : boolean,
	autoUpdate    : boolean,
	widthAuto     : boolean,
	heightAuto    : boolean,
	documentMixed : boolean,
	padding : {
		t : number,
		r : number,
		b : number,
		l : number
	},
	overflowAmount : {
		x : number,
		y : number
	},
	hideOverflow : {
		x  : boolean,
		y  : boolean,
		xs : boolean,
		ys : boolean
	},
	hasOverflow : {
		x : boolean,
		y : boolean
	},
	contentScrollSize : {
		width  : number,
		height : number
	},
	viewportSize : {
		width  : number,
		height : number
	},
	hostSize : {
		width  : number,
		height : number
	}
}

type Position = number | string;

type Coordinates =
  { x: Position, y: Position } |
  { l: Position, t: Position } |
  { left: Position, top: Position } |
  [Position, Position] |
  Position |
  HTMLElement |
  {
    el       : HTMLElement ,
    axis     : string,
    block    : string | ReadonlyArray<string>,
    margin   : number | ReadonlyArray<number> | boolean
  };

interface OverlayScrollbars {
  options(): OverlayScrollbarsOptions;
  options<T = {} | undefined | null>(optionName: string): T;
  options(optionName: string, optionValue: any);
  options(options: OverlayScrollbarsOptions);

  update(force?: boolean);
  sleep();
  scroll(): ScrollInfo;
  scroll(coordinates: Coordinates, duration?: number, easing?: string | ReadonlyArray<string>, complete?: Function);
  scroll(coordinates: Coordinates, options?: object);
  scrollStop();
  getElements(): Elements;
  getState(): State;
  getState<T = {} | undefined | null>(stateProperty): T;
  destroy();
}


declare interface OverlayScrollbarsStatic {
  (element: HTMLElement, options: OverlayScrollbarsOptions): OverlayScrollbars;
  (element: HTMLElement): OverlayScrollbars | undefined;

  (elements:  NodeListOf<Element> | ReadonlyArray<Element>, options: OverlayScrollbarsOptions): Array<OverlayScrollbars>;
  (elements: NodeListOf<Element> | ReadonlyArray<Element>): Array<OverlayScrollbars>;

  globals(): {
    defaultOptions          : {},
    autoUpdateLoop          : boolean,
    autoUpdateRecommended   : boolean,
    supportMutationObserver : boolean,
    supportResizeObserver   : boolean,
    supportPassiveEvents    : boolean,
    supportTransform        : boolean,
    supportTransition       : boolean,
    restrictedMeasuring     : boolean,
    nativeScrollbarStyling  : boolean,
    cssCalc                 : string,
    nativeScrollbarSize : {
      x : number,
      y : number
    },
    nativeScrollbarIsOverlaid : {
      x : boolean,
      y : boolean
    },
    overlayScrollbarDummySize : {
      x : number,
      y : number
    },
    rtlScrollBehavior : {
      i : boolean,
      n : boolean
    }
  };

  defaultOptions(): OverlayScrollbarsOptions;

  defaultOptions(newDefaultOptions: OverlayScrollbarsOptions): OverlayScrollbarsOptions;
}


declare module "overlayscrollbars" {
  var x: OverlayScrollbarsStatic;
  export = x;
}

Handling img elements

hello,

scroll bar (in my case horizontal, i didnt check vertical) didnt show/appearing... only after window resize or in my case-when i activate next tab where i other img gallery) ... for test i using your css and css theme... problem come up when site is uploaded on server (or test locallhost) but when i using a brackets live view every thing is ok... on classic firefox and chrome there is no problem also (everywhere)

in console i get massage: "This site appears to use a scroll-linked positioning effect. This may not work well with asynchronous panning; see https://developer.mozilla.org/docs/Mozilla/Performance/ScrollLinkedEffects for further details and to join the discussion on related tools and features!"

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.