jQuery custom content scroller
jQuery custom content scroller
Last updated on Jul 11, 2016
Originally published on August 1, 2010 by malihu, under Plugins.
Highly customizable custom scrollbar jQuery plugin. Features include vertical and/or horizontal scrollbar(s), adjustable scrolling momentum, mouse-wheel (via jQuery mousewheel plugin), keyboard and touch support, ready-to-use themes and customization via CSS, RTL direction support, option parameters for full control of scrollbar functionality, methods for triggering actions like scroll-to, update, destroy etc., user-defined callbacks and more.
view demo Scrollbar themes
more
Nested scrollbars
Callbacks demo
RTL direction
disable/destroy methods
download Release archive
Project on GitHub
Current version 3.1.5 (Changelog)
Upgrading from version 2
When upgrading from version 2.x to 3.x it’s important to use version 3 CSS and .png files. Version 3 is backwards compatible but it’s also a huge overhaul. One significant change is that you don’t need to call the update method manually (the script does it automatically). For more info see changelog.
Version 2 is still maintained and updated here.
- Get started
- Configuration
- Methods
- Styling
- Callbacks
- Code examples and tutorials
- FAQ
How to use it
Get started by downloading the archive which contains the plugin files (and a large amount of HTML demos and examples). Extract and upload jquery.mCustomScrollbar.concat.min.js, jquery.mCustomScrollbar.css and mCSB_buttons.png to your web server (alternatively you can load plugin files from a CDN).
Instead of hosting the plugin files on your web server, you can load them directly from a CDN like jsdelivr, Github etc.
- jsdelivr versioned/minified
- //cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/jquery.mCustomScrollbar.concat.min.js
- //cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/jquery.mCustomScrollbar.min.css
- //cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/mCSB_buttons.png
- Github latest/minified
- //malihu.github.io/custom-scrollbar/jquery.mCustomScrollbar.concat.min.js
- //malihu.github.io/custom-scrollbar/jquery.mCustomScrollbar.min.css
- //malihu.github.io/custom-scrollbar/mCSB_buttons.png
HTML
Include jquery.mCustomScrollbar.css in the head tag your HTML document (more info)
jquery.mCustomScrollbar.css contains the styling of the custom scrollbar and themes. It should normally be included in the head tag of your html (typically before any script tags). If you wish to reduce http requests and/or have all your website stylesheet in a single file, you should move/copy scrollbars styling in your main CSS document.
mCSB_buttons.png contains all the button arrows (up, down, left and right) as image sprites for all scrollbar themes. The plugin archive contains the PSD source (source-files/mCSB_buttons.psd) so you can change them or add your own. This file should be in the same directory with plugin stylesheet.
<link rel="stylesheet" href="/path/to/jquery.mCustomScrollbar.css" />
Include jQuery library (if your project doesn’t use it already) and jquery.mCustomScrollbar.concat.min.js in the head tag or at the very bottom of your document, just before the closing body tag
Some frameworks and CMS include jQuery library in the head tag to make sure it’s loaded when other scripts request it. Usually, including .js files on the bottom of the HTML document (just before the closing body tag) is recommended for better performance. In any case, jQuery must be included first, before plugin scripts.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/path/to/jquery.mCustomScrollbar.concat.min.js"></script>
CSS
The element(s) you want to add scrollbar(s) should have the typical CSS properties of an overflowed block which are a height (or max-height) value, an overflow value of auto (or hidden) and content long enough to require scrolling. For horizontal scrollbar, the element should have a width (or max-width) value set.
If you prefer to set your element’s height/width via javascript, you can use the setHeight/setWidth option parameters.
Initialization
Initialize via javascript
After files inclusion, call mCustomScrollbar function on the element selector you want to add the scrollbar(s)
<script>
(function($){
$(window).on("load",function(){
$(".content").mCustomScrollbar();
});
})(jQuery);
</script>
more info
The code is wrapped in (function($){ ... })(jQuery);. This ensures no conflict between jQuery and other libraries using $ shortcut (see Avoiding Conflicts with Other Libraries for more info). The plugin function is called in $(window).on("load") so it executes after all page elements (like images) are loaded.
You can change the function selector ".content" to any selector you want (an element id, class name, js variable etc.). For instance, if you want custom scrollbars to apply on the element with id content-1, you simply do:
$("#content-1").mCustomScrollbar();
You may also have multiple selectors by inserting comma separated values
$(".content,#content-1").mCustomScrollbar();
The above code adds custom scrollbars to a)every element with class name content and b)the element with id content-1.
Additionally, you may want to call mCustomScrollbar multiple times within a page in order to set different options (configuration and option parameters explained below) for each selector
<script>
(function($){
$(window).on("load",function(){
$("#vertical-content").mCustomScrollbar({
theme:"light-3",
scrollButtons:{
enable:true
}
});
$("#horizontal-content").mCustomScrollbar({
axis:"x",
theme:"3d"
});
});
})(jQuery);
</script>
Initialize via HTML
Add the class mCustomScrollbar to any element you want to add custom scrollbar(s) with default options. Optionally, set its axis via the HTML data attribute data-mcs-axis (e.g. "x" for horizontal and "y" for vertical) and its theme via data-mcs-theme. For example:
<div class="mCustomScrollbar" data-mcs-theme="dark">
<!-- your content -->
</div>
Basic configuration & option parameters
axis
By default, the script applies a vertical scrollbar. To add a horizontal or 2-axis scrollbars, invoke mCustomScrollbar function with the axis option set to "x" or "yx" respectively
$(".content").mCustomScrollbar({
axis:"x" // horizontal scrollbar
});
$(".content").mCustomScrollbar({
axis:"yx" // vertical and horizontal scrollbar
});
theme
To quickly change the appearance of the scrollbar, set the theme option parameter to any of the ready-to-use themes available in jquery.mCustomScrollbar.css, for example:
$(".content").mCustomScrollbar({
theme:"dark"
});
Configuration
You can configure your scrollbar(s) using the following option parameters on mCustomScrollbar function
Usage $(selector).mCustomScrollbar({ option: value });
setWidth: false
Set the width of your content (overwrites CSS width), value in pixels (integer) or percentage (string).
setHeight: false
Set the height of your content (overwrites CSS height), value in pixels (integer) or percentage (string).
setTop: 0
Set the initial css top property of content, accepts string values (css top position).
Example: setTop: "-100px".
setLeft: 0
Set the initial css left property of content, accepts string values (css left position).
Example: setLeft: "-100px".
axis: "string"
Define content’s scrolling axis (the type of scrollbars added to the element: vertical and/of horizontal).
Available values: "y", "x", "yx".
- axis: "y" – vertical scrollbar (default)
- axis: "x" – horizontal scrollbar
- axis: "yx" – vertical and horizontal scrollbars
scrollbarPosition: "string"
Set the position of scrollbar in relation to content.
Available values: "inside", "outside".
Setting scrollbarPosition: "inside" (default) makes scrollbar appear inside the element. Setting scrollbarPosition: "outside" makes scrollbar appear outside the element. Note that setting the value to "outside" requires your element (or parent elements) to have CSS position: relative (otherwise the scrollbar will be positioned in relation to document’s root element).
scrollInertia: integer
Set the amount of scrolling momentum as animation duration in milliseconds.
Higher value equals greater scrolling momentum which translates to smoother/more progressive animation. Set to 0 to disable.
autoDraggerLength: boolean
Enable or disable auto-adjusting scrollbar dragger length in relation to scrolling amount (same bahavior with browser’s native scrollbar).
Set autoDraggerLength: false when you want your scrollbar to (always) have a fixed size.
autoHideScrollbar: boolean
Enable or disable auto-hiding the scrollbar when inactive.
Setting autoHideScrollbar: true will hide the scrollbar(s) when scrolling is idle and/or cursor is out of the scrolling area.
Please note that some special themes like “minimal” overwrite this option.
autoExpandScrollbar: boolean
Enable or disable auto-expanding the scrollbar when cursor is over or dragging the scrollbar.
alwaysShowScrollbar: integer
Always keep scrollbar(s) visible, even when there’s nothing to scroll.
- alwaysShowScrollbar: 0 – disable (default)
- alwaysShowScrollbar: 1 – keep dragger rail visible
- alwaysShowScrollbar: 2 – keep all scrollbar components (dragger, rail, buttons etc.) visible
snapAmount: integer
Make scrolling snap to a multiple of a fixed number of pixels. Useful in cases like scrolling tabular data, image thumbnails or slides and you need to prevent scrolling from stopping half-way your elements. Note that your elements must be of equal width or height in order for this to work properly.
To set different values for vertical and horizontal scrolling, use an array: [y,x]
snapOffset: integer
Set an offset (in pixels) for the snapAmount option. Useful when for example you need to offset the snap amount of table rows by the table header.
mouseWheel:{ enable: boolean }
Enable or disable content scrolling via mouse-wheel.
mouseWheel:{ scrollAmount: integer }
Set the mouse-wheel scrolling amount (in pixels). The default value "auto" adjusts scrolling amount according to scrollable content length.
mouseWheel:{ axis: "string" }
Define the mouse-wheel scrolling axis when both vertical and horizontal scrollbars are present.
Set axis: "y" (default) for vertical or axis: "x" for horizontal scrolling.
mouseWheel:{ preventDefault: boolean }
Prevent the default behaviour which automatically scrolls the parent element when end or beginning of scrolling is reached (same bahavior with browser’s native scrollbar).
mouseWheel:{ deltaFactor: integer }
Set the number of pixels one wheel notch scrolls. The default value “auto” uses the OS/browser value.
mouseWheel:{ normalizeDelta: boolean }
Enable or disable mouse-wheel (delta) acceleration. Setting normalizeDelta: true translates mouse-wheel delta value to -1 or 1.
mouseWheel:{ invert: boolean }
Invert mouse-wheel scrolling direction. Set to true to scroll down or right when mouse-wheel is turned upwards.
mouseWheel:{ disableOver: [array] }
Set the tags that disable mouse-wheel when cursor is over them.
Default value: ["select","option","keygen","datalist","textarea"]
scrollButtons:{ enable: boolean }
Enable or disable scrollbar buttons.
scrollButtons:{ scrollAmount: integer }
Set the buttons scrolling amount (in pixels). The default value "auto" adjusts scrolling amount according to scrollable content length.
scrollButtons:{ scrollType: "string" }
Define the buttons scrolling type/behavior.
- scrollType: "stepless" – continuously scroll content while pressing the button (default)
- scrollType: "stepped" – each button click scrolls content by a certain amount (defined in scrollAmount option above)
scrollButtons:{ tabindex: integer }
Set a tabindex value for the buttons.
keyboard:{ enable: boolean }
Enable or disable content scrolling via the keyboard.
The plugin supports the directional arrows (top, left, right and down), page-up (PgUp), page-down (PgDn), Home and End keys.
keyboard:{ scrollAmount: integer }
Set the keyboard arrows scrolling amount (in pixels). The default value "auto" adjusts scrolling amount according to scrollable content length.
keyboard:{ scrollType: "string" }
Define the keyboard arrows scrolling type/behavior.
- scrollType: "stepless" – continuously scroll content while pressing the arrow key (default)
- scrollType: "stepped" – each key release scrolls content by a certain amount (defined in scrollAmount option above)
contentTouchScroll: integer
Enable or disable content touch-swipe scrolling for touch-enabled devices.
To completely disable, set contentTouchScroll: false.
Integer values define the axis-specific minimum amount required for scrolling momentum (default: 25).
documentTouchScroll: boolean
Enable or disable document touch-swipe scrolling for touch-enabled devices.
advanced:{ autoExpandHorizontalScroll: boolean }
Auto-expand content horizontally (for "x" or "yx" axis).
If set to true, content will expand horizontally to accommodate any floated/inline-block elements.
Setting its value to 2 (integer) forces the non scrollHeight/scrollWidth method. A value of 3 forces the scrollHeight/scrollWidth method.
advanced:{ autoScrollOnFocus: "string" }
Set the list of elements/selectors that will auto-scroll content to their position when focused.
For example, when pressing TAB key to focus input fields, if the field is out of the viewable area the content will scroll to its top/left position (same bahavior with browser’s native scrollbar).
To completely disable this functionality, set autoScrollOnFocus: false.
Default: "input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']"
advanced:{ updateOnContentResize: boolean }
Update scrollbar(s) automatically on content, element or viewport resize.
The value should be true (default) for fluid layouts/elements, adding/removing content dynamically, hiding/showing elements etc.
advanced:{ updateOnImageLoad: boolean }
Update scrollbar(s) automatically each time an image inside the element is fully loaded.
Default value is auto which triggers the function only on "x" and "yx" axis (if needed).
The value should be true when your content contains images and you need the function to trigger on any axis.
advanced:{ updateOnSelectorChange: "string" }
Update scrollbar(s) automatically when the amount and size of specific selectors changes.
Useful when you need to update the scrollbar(s) automatically, each time a type of element is added, removed or changes its size.
For example, setting updateOnSelectorChange: "ul li" will update scrollbars each time list-items inside the element are changed.
Setting the value to true, will update scrollbars each time any element is changed.
To disable (default) set to false.
advanced:{ extraDraggableSelectors: "string" }
Add extra selector(s) that’ll release scrollbar dragging upon mouseup, pointerup, touchend etc.
Example: extraDraggableSelectors: ".myClass, #myID"
advanced:{ releaseDraggableSelectors: "string" }
Add extra selector(s) that’ll allow scrollbar dragging upon mousemove/up, pointermove/up, touchend etc.
Example: releaseDraggableSelectors: ".myClass, #myID"
advanced:{ autoUpdateTimeout: integer }
Set the auto-update timeout in milliseconds.
Default timeout: 60
theme: "string"
Set the scrollbar theme.
View all ready-to-use themes
All themes are contained in plugin’s CSS file (jquery.mCustomScrollbar.css).
Default theme: "light"
callbacks:{
onCreate: function(){}
}
A function to call when plugin markup is created.
Example:
callbacks:{
onCreate:function(){
console.log("Plugin markup generated");
}
}
callbacks:{
onInit: function(){}
}
A function to call when scrollbars have initialized (demo).
Example:
callbacks:{
onInit:function(){
console.log("Scrollbars initialized");
}
}
callbacks:{
onScrollStart: function(){}
}
A function to call when scrolling starts (demo).
Example:
callbacks:{
onScrollStart:function(){
console.log("Scrolling started...");
}
}
callbacks:{
onScroll: function(){}
}
A function to call when scrolling is completed (demo).
Example:
callbacks:{
onScroll:function(){
console.log("Content scrolled...");
}
}
callbacks:{
whileScrolling: function(){}
}
A function to call while scrolling is active (demo).
Example:
callbacks:{
whileScrolling:function(){
console.log("Scrolling...");
}
}
callbacks:{
onTotalScroll: function(){}
}
A function to call when scrolling is completed and content is scrolled all the way to the end (bottom/right) (demo).
Example:
callbacks:{
onTotalScroll:function(){
console.log("Scrolled to end of content.");
}
}
callbacks:{
onTotalScrollBack: function(){}
}
A function to call when scrolling is completed and content is scrolled back to the beginning (top/left) (demo).
Example:
callbacks:{
onTotalScrollBack:function(){
console.log("Scrolled back to the beginning of content.");
}
}
callbacks:{
onTotalScrollOffset: integer
}
Set an offset for the onTotalScroll option.
For example, setting onTotalScrollOffset: 100 will trigger the onTotalScroll callback 100 pixels before the end of scrolling is reached.
callbacks:{
onTotalScrollBackOffset: integer
}
Set an offset for the onTotalScrollBack option.
For example, setting onTotalScrollBackOffset: 100 will trigger the onTotalScrollBack callback 100 pixels before the beginning of scrolling is reached.
callbacks:{
alwaysTriggerOffsets: boolean
}
Set the behavior of calling onTotalScroll and onTotalScrollBack offsets.
By default, callback offsets will trigger repeatedly while content is scrolling within the offsets.
Set alwaysTriggerOffsets: false when you need to trigger onTotalScroll and onTotalScrollBack callbacks once, each time scroll end or beginning is reached.
callbacks:{
onOverflowY: function(){}
}
A function to call when content becomes long enough and vertical scrollbar is added.
Example:
callbacks:{
onOverflowY:function(){
console.log("Vertical scrolling required");
}
}
callbacks:{
onOverflowX: function(){}
}
A function to call when content becomes wide enough and horizontal scrollbar is added.
Example:
callbacks:{
onOverflowX:function(){
console.log("Horizontal scrolling required");
}
}
callbacks:{
onOverflowYNone: function(){}
}
A function to call when content becomes short enough and vertical scrollbar is removed.
Example:
callbacks:{
onOverflowYNone:function(){
console.log("Vertical scrolling is not required");
}
}
callbacks:{
onOverflowXNone: function(){}
}
A function to call when content becomes narrow enough and horizontal scrollbar is removed.
Example:
callbacks:{
onOverflowXNone:function(){
console.log("Horizontal scrolling is not required");
}
}
callbacks:{
onBeforeUpdate: function(){}
}
A function to call right before scrollbar(s) are updated.
Example:
callbacks:{
onBeforeUpdate:function(){
console.log("Scrollbars will update");
}
}
callbacks:{
onUpdate: function(){}
}
A function to call when scrollbar(s) are updated.
Example:
callbacks:{
onUpdate:function(){
console.log("Scrollbars updated");
}
}
callbacks:{
onImageLoad: function(){}
}
A function to call each time an image inside the element is fully loaded and scrollbar(s) are updated.
Example:
callbacks:{
onImageLoad:function(){
console.log("Image loaded");
}
}
callbacks:{
onSelectorChange: function(){}
}
A function to call each time a type of element is added, removed or changes its size and scrollbar(s) are updated.
Example:
callbacks:{
onSelectorChange:function(){
console.log("Scrollbars updated");
}
}
live: "string"
Enable or disable applying scrollbar(s) on all elements matching the current selector, now and in the future.
Set live: true when you need to add scrollbar(s) on elements that do not yet exist in the page. These could be elements added by other scripts or plugins after some action by the user takes place (e.g. lightbox markup may not exist untill the user clicks a link).
If you need at any time to disable or enable the live option, set live: "off" and "on" respectively.
You can also tell the script to disable live option after the first invocation by setting live: "once".
liveSelector: "string"
Set the matching set of elements (instead of the current selector) to add scrollbar(s), now and in the future.
Plugin methods
Ways to execute various plugin actions programmatically from within your script(s).
update
Usage $(selector).mCustomScrollbar("update");
Call the update method to manually update existing scrollbars to accommodate new content or resized element(s). This method is by default called automatically by the script (via updateOnContentResize option) when the element itself, its content or scrollbar size changes.
view examples
/* initialize plugin with auto-update options disabled */
$(selector).mCustomScrollbar({
advanced:{
updateOnContentResize: false,
updateOnImageLoad: false
}
});
/* at some point in your js script/code update scrollbar manually */
$(selector).mCustomScrollbar("update");
scrollTo
Usage $(selector).mCustomScrollbar("scrollTo",position,options);
Call the scrollTo method to programmatically scroll the content to the position parameter (demo).
position parameter
Position parameter can be:
- "string"
- e.g. element selector: "#element-id"
- e.g. special pre-defined position: "bottom"
- e.g. number of pixels less/more: "-=100"/"+=100"
- integer
- e.g. number of pixels: 100
- [array]
- e.g. different y/x position: [100,50]
- object/function
- e.g. jQuery object: $("#element-id")
- e.g. js object: document.getelementbyid("element-id")
- e.g. function: function(){ return 100; }
Pre-defined position strings:
- "bottom" – scroll to bottom
- "top" – scroll to top
- "right" – scroll to right
- "left" – scroll to left
- "first" – scroll to the position of the first element within content
- "last" – scroll to the position of the last element within content
view examples
Scroll to element with id “#el-1″
$(selector).mCustomScrollbar("scrollTo","#el-1");
Scroll to top
$(selector).mCustomScrollbar("scrollTo","top");
Scroll by 100 pixels down or right
var val=100;
$(selector).mCustomScrollbar("scrollTo","-="+val);
Scroll by 100 pixels up or left
$(selector).mCustomScrollbar("scrollTo","+=100");
Scroll by 100 pixels down and by 50 pixels right
$(selector).mCustomScrollbar("scrollTo",["-=100","-=50"]);
Scroll to the fifth paragraph
$(selector).mCustomScrollbar("scrollTo",$("p:eq(4)"));
Scroll to the last element within your content
$(selector).mCustomScrollbar("scrollTo","last");
Scroll to some variable value
var val=document.getelementbyid("element-id");
$(selector).mCustomScrollbar("scrollTo",val);
Scroll to 300 pixels
$(selector).mCustomScrollbar("scrollTo",300);