jQuery custom content scroller
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.
Current version 3.1.5 (Changelog)
Upgrading from version 2
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).
HTML
Include jquery.mCustomScrollbar.css in the head tag your HTML document (more info)
<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
<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>
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 scrollbaraxis: "yx"
– vertical and horizontal scrollbars
scrollbarPosition: "string"
- Set the position of scrollbar in relation to content.
Available values:"inside"
,"outside"
.
SettingscrollbarPosition: "inside"
(default) makes scrollbar appear inside the element. SettingscrollbarPosition: "outside"
makes scrollbar appear outside the element. Note that setting the value to"outside"
requires your element (or parent elements) to have CSSposition: 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 to0
to disable.
autoDraggerLength: boolean
- Enable or disable auto-adjusting scrollbar dragger length in relation to scrolling amount (same bahavior with browser’s native scrollbar).
SetautoDraggerLength: false
when you want your scrollbar to (always) have a fixed size.
autoHideScrollbar: boolean
- Enable or disable auto-hiding the scrollbar when inactive.
SettingautoHideScrollbar: 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 visiblealwaysShowScrollbar: 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.
Setaxis: "y"
(default) for vertical oraxis: "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, setcontentTouchScroll: 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 totrue
, content will expand horizontally to accommodate any floated/inline-block elements.
Setting its value to2
(integer) forces the non scrollHeight/scrollWidth method. A value of3
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, setautoScrollOnFocus: 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 betrue
(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 isauto
which triggers the function only on"x"
and"yx"
axis (if needed).
The value should betrue
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, settingupdateOnSelectorChange: "ul li"
will update scrollbars each time list-items inside the element are changed.
Setting the value totrue
, will update scrollbars each time any element is changed.
To disable (default) set tofalse
.
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, settingonTotalScrollOffset: 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, settingonTotalScrollBackOffset: 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.
SetalwaysTriggerOffsets: 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.
Setlive: 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, setlive: "off"
and"on"
respectively.
You can also tell the script to disable live option after the first invocation by settinglive: "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.
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"
- e.g. element selector:
integer
- e.g. number of pixels:
100
- e.g. number of pixels:
[array]
- e.g. different y/x position:
[100,50]
- e.g. different y/x position:
object/function
- e.g. jQuery object:
$("#element-id")
- e.g. js object:
document.getelementbyid("element-id")
- e.g. function:
function(){ return 100; }
- e.g. jQuery object:
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
Method options
scrollInertia: integer
- Scroll-to duration, value in milliseconds.
Example:
$(selector).mCustomScrollbar("scrollTo","bottom",{ scrollInertia:3000 });
scrollEasing: "string"
- Scroll-to animation easing, values:
"linear"
,"easeOut"
,"easeInOut"
.
Example:
$(selector).mCustomScrollbar("scrollTo","bottom",{ scrollEasing:"easeOut" });
moveDragger: boolean
- Scroll scrollbar dragger (instead of content).
Example:
$(selector).mCustomScrollbar("scrollTo",80,{ moveDragger:true });
timeout: integer
- Set a timeout for the method (the default timeout is 60 ms in order to work with automatic scrollbar update), value in milliseconds.
Example:
$(selector).mCustomScrollbar("scrollTo","top",{ timeout:1000 });
callbacks: boolean
- Trigger user defined callbacks after scroll-to completes.
Example:
$(selector).mCustomScrollbar("scrollTo","left",{ callbacks:false });
stop
Usage $(selector).mCustomScrollbar("stop");
Stops any running scrolling animations (usefull when you wish to interupt a previously scrollTo method call).
disable
Usage $(selector).mCustomScrollbar("disable");
Calling disable method will temporarily disable the scrollbar (demo). Disabled scrollbars can be re-enable by calling the update method.
To disable the scrollbar and reset its content position, set the method’s reset parameter to true
$(selector).mCustomScrollbar("disable",true);
destroy
Usage $(selector).mCustomScrollbar("destroy");
Calling destroy method will completely remove the custom scrollbar and return the element to its original state (demo).
Scrollbar styling & themes
You can design and visually customize your scrollbars with pure CSS, using jquery.mCustomScrollbar.css which contains the default/basic styling and all scrollbar themes.
The easiest/quickest way is to select a ready-to-use scrollbar theme. For example:
$(selector).mCustomScrollbar({ theme:"dark" });
You can modify the default styling or any theme either directly in jquery.mCustomScrollbar.css or by overwriting the CSS rules in another stylesheet.
Creating a new scrollbar theme
Create a name for your theme (e.g. “my-theme”) and set it as the value of the theme option
$(selector).mCustomScrollbar({ theme:"my-theme" });
Your element will get the class “mCS-my-theme” (your theme-name with “mCS” prefix), so you can create your CSS using the .mCS-my-theme
in your rules. For instance:
.mCS-my-theme.mCSB_scrollTools .mCSB_dragger .mCSB_dragger_bar{ background-color: red; } .mCS-my-theme.mCSB_scrollTools .mCSB_draggerRail{ background-color: white; } /* and so on... */
In the same manner you can clone any existing theme (e.g. “dark”), change its selector (e.g. .mCS-dark
) to your own theme name (e.g. .mCS-my-theme
) and modify its CSS rules.
Scrollbar markup
The plugin applies specific id (unique) and/or classes to every scrollbar element/component, meaning that you can target and modify any scrollbar in more than one ways.
For example, every element with a scrollbar gets a unique class in the form of _mCS_1
, _mCS_2
etc. Every scrollbar container element gets a unique id in the form of mCSB_1_scrollbar_vertical
, mCSB_2_scrollbar_vertical
etc. Every scrollbar dragger gets a unique id in the form of mCSB_1_dragger_vertical
, mCSB_2_dragger_vertical
etc. in addition to the class mCSB_dragger
. All these mean that you can do stuff like:
._mCS_1 .mCSB_dragger .mCSB_dragger_bar{ background-color: red; } ._mCS_2 .mCSB_dragger .mCSB_dragger_bar{ background-color: green; } #mCSB_3_dragger_vertical .mCSB_dragger_bar{ background-color: blue; } #mCSB_1_scrollbar_vertical .mCSB_dragger{ height: 100px; } #mCSB_1_scrollbar_horizontal .mCSB_dragger{ width: 100px; } .mCSB_1_scrollbar .mCSB_dragger .mCSB_draggerRail{ width: 4px; }
User-defined callbacks
You can trigger your own js function(s) by calling them inside mCustomScrollbar callbacks option parameter
$(".content").mCustomScrollbar({ callbacks:{ onScroll:function(){ myCustomFn(this); } } }); function myCustomFn(el){ console.log(el.mcs.top); }
In the example above, each time a scroll event ends and content has stopped scrolling, the content’s top position will be logged in browser’s console. There are available callbacks for each step of the scrolling event:
onScrollStart
– triggers the moment a scroll event startswhileScrolling
– triggers while scroll event is runningonScroll
– triggers when a scroll event completesonTotalScroll
– triggers when content has scrolled all the way to bottom or rightonTotalScrollBack
– triggers when content has scrolled all the way back to top or left
You can set an offset value (pixels) for both onTotalScroll
and onTotalScrollBack
by setting onTotalScrollOffset
and onTotalScrollBackOffset
respectively (view example).
By default, onTotalScroll
and onTotalScrollBack
callbacks are triggered repeatedly. To prevent multiple calls when content is within their offset, set alwaysTriggerOffsets
option to false
(view example).
Additional callbacks:
onInit
onOverflowY
onOverflowX
onOverflowYNone
onOverflowXNone
onUpdate
onImageLoad
onSelectorChange
Returning values
The script returns a number of values and objects related to scrollbar that you can use in your own functions
this
– the original element containing the scrollbar(s)this.mcs.content
– the original content wrapper as jquery objectthis.mcs.top
– content’s top position (pixels)this.mcs.left
– content’s left position (pixels)this.mcs.draggerTop
– scrollbar dragger’s top position (pixels)this.mcs.draggerLeft
– scrollbar dragger’s left position (pixels)this.mcs.topPct
– content vertical scrolling percentagethis.mcs.leftPct
– content horizontal scrolling percentagethis.mcs.direction
– content’s scrolling direction (y or x)
Plugin-specific jQuery expressions
$("#myID:mcsInView")
- Select element(s) in your content that are within scrollable viewport.
As condition:$("#myID").is(":mcsInView");
$(".content:mcsOverflow")
- Select overflowed element(s) with visible scrollbar.
As condition:$(".content").is(":mcsOverflow");
$("#myID:mcsInSight")
$("#myID:mcsInSight(exact)")
- Select element(s) in your content that are in view of the scrollable viewport. Using the
exact
parameter will include elements that have any part of them (even 1 pixel) in view of the scrollable viewport.
As condition:$("#myID").is(":mcsInSight");
,$("#myID").is(":mcsInSight(exact)");
Plugin dependencies & requirements
- jQuery version 1.6.0 or higher
- Mouse-wheel support
License
This work is released under the MIT License.
You are free to use, study, improve and modify it wherever and however you like.
https://opensource.org/licenses/MIT
Donating helps greatly in developing and updating free software and running this blog 🙂
Hello.
While using onTotalScroll and onTotalScrollBack callbacks to update content of vertical news list I’ve noticed the following behaviour:
1. When the dragger hits the bottom the content is added at the bottom, the container stays in place and the dragger adjusts its height and position – moves up relative to its previous position – so it can be moved to bottom again to trigger onTotalScroll. So all is good.
2. When the dragger hits the top the content is added at the top, the container stays in place but visually due to added content it appears as though the container is moved down, the dragger adjusts its height and stays in place – at the topmost position – so it can’t be moved to the top again, you need first to move it down.
To make it look like the container stays in place after adding content at the top I’ve tried scrolling to the element that prior to updating the content was first in the list but this is very noticeable.
So my question is: is it somehow possible to make it look like the container always stays in place when adding content at the top?
E.g. it could be some function that could freeze the container’s position with the option to signify that the content is being added at the top or at the bottom so that the css of the container could be adjusted accordingly.
Yes (with a bit of extra code).
Your idea of using the scrollTo method is the correct way to do it. You need to set scrollInertia option parameter of the method to 0, so it scrolls “instantly” and also to find the proper position to scroll-to.
The best way to find where to scroll-to is to subtract the “old” content height from the “new” one (you should be able to store the “old” content height in a variable before the new content is loaded). Then, you can use the result and subtract it from the current content position.
It sounds a bit complicated but it’s not… for example:
var oldContentHeight=$(".content .mCSB_container").innerHeight(); /* your code that loads new content... */ var heightDiff=$(".content .mCSB_container").innerHeight()-oldContentHeight; $(".content").mCustomScrollbar("scrollTo","-="+heightDiff,{scrollInertia:0});
I’ve made a simple but fully working example where you can see and grab the code here:
http://manos.malihu.gr/repository/custom-scrollbar/tests/infinite_scroll_reversed_demo.html
Thank you for the answer.
But unfortunately even scrollInertia 0 does not make the jitter go away. In your example this jitter is seen during the first content addition. It is not seen during the following additions because the content is the same.
Ah I see…
This happens due to the 60 millisecond timeout of the method. If you need a quick fix (until I update the script), you can edit jquery.mCustomScrollbar.js, find line 619 and change 60 to 0.
I’ll probably introduce an option parameter for this on the next update (in a few days).
Unfortunately changing this timeout value to 0 or making the code from that setTimeout on lines 61* synchronous does not resolve the problem – the content’s jitter is still noticeable (in Firefox).
Also I’ve noticed another kind of jitter – the dragger’s jitter. Sometimes when the dragger is large it is noticeable how after adding content at the top it first jumps to its new position and then adjusts its height (when updateOnContentResize is true) or vice versa (when updateOnContentResize is false and I first update scrollbar and then scroll). Or maybe I’m already seeing things after looking at the scrolling content too much.
Sorry for the late reply!
The jitter in Firefox is fixed in version 3.0.4 (just released). So check the demo one more time and download/use version 3.0.4.
The scroll-to timeout can now be set via the timeout option of the method like this:
$(selector).mCustomScrollbar("scrollTo",to,{scrollInertia:0,timeout:0});
The second jitter you noticed should also be eliminated with new version, especially when using updateOnContentResize:false with the update method.
Hello Malihu,
i have an “Highslide Thumbnail Viewer” and i try to call an iFrame to give it new Scrollbars.
The DIV i will call is: .highslide-body iframe.
I give the iframe a new height…
It not works…
I need a help!
Thanks
Hi,
You can check the iframe example (included in the download archive) here: https://github.com/malihu/malihu-custom-scrollbar-plugin/blob/master/examples/iframe_example.html
The plugin cannot manipulate directly the inner content of an iframe as it’s essentially another document. You’ll need to wrap the iframe with another div and call mCustomScrollbar function on this div (which should have overflow and height properties set).
Hello sir, i have a problem with the js file. by using this stylish scrollbar i can’t use .toggle() function anymore. why it is conflicting with the jquery 1.7.2 ?
and second please tell me how to make the scrollbar speed fast.
Hello,
To change the scrolling momentum, use the
scrollInertia
option parameter. To change mouse-wheel “speed” use themouseWheel:{ scrollAmount: integer }
option parameter. For example:$(selector).mCustomScrollbar({ scrollInertia: 950, mouseWheel:{ scrollAmount: 100 } });
For the first part of your question, I need more info about the problem or maybe a link to check it online.
your plugin is awesome i integrate it in one of my websites.
I would like to integrate it in a wordpress site, which would be the best approch to do this?
Greetings
Hi,
The following is a good way of adding the plugin in your theme manually:
1. Create a new folder inside your theme directory and name it “custom-scrollbar”. Place the jquery.mCustomScrollbar.concat.min.js, jquery.mCustomScrollbar.css and mCSB_buttons.png files inside it.
2. Create a new js file: jquery.mCustomScrollbar.init.js inside “custom-scrollbar” folder. Insert the following code in it, replacing selector with your element(s) and options:
(function($){ $(window).load(function(){ $(selector).mCustomScrollbar({ theme:"dark" }); }); })(jQuery);
3. Edit your themes functions.php and insert the following PHP code which loads plugin’s css and js files in your templates:
function custom_scrollbar_init() { if(!is_admin()){ /* add plugin stylesheet */ wp_enqueue_style( 'customscrollbar-css', get_template_directory_uri() . '/custom-scrollbar/jquery.mCustomScrollbar.css' ); /* add plugin main js */ wp_enqueue_script( 'customscrollbar-js', get_template_directory_uri() . '/custom-scrollbar/jquery.mCustomScrollbar.concat.min.js', array('jquery'), '3.0.3', true ); /* add plugin init js */ wp_enqueue_script( 'customscrollbar-init-js', get_template_directory_uri() . '/custom-scrollbar/jquery.mCustomScrollbar.init.js', array('jquery', 'customscrollbar-js'), '3.0.3', true ); } } add_action('wp_enqueue_scripts', 'custom_scrollbar_init');
4. Create your content and elements that’ll have a custom scrollbar and you’re done.
You could of course skip the creation of jquery.mCustomScrollbar.init.js and either place its code directly in your theme’s footer.php or main js file or just add the mCustomScrollbar class to your element(s) to apply the scrollbar with the default options.
it Works like a charm thank you very much
🙂
Hi!
Thank you for your plugin, but i have two questions:
1) Is it normal behavior?
// callbacks works fine
$('#content').mCustomScrollbar({callbacks: { onScroll: function() { console.log('scroll') } }})
// callbacks don’t works
$('#content').mCustomScrollbar(); $('#content').mCustomScrollbar({callbacks: { onScroll: function() { console.log('scroll') } }})
2) I write $(‘#content’).mCustomScrollbar(); but #content is empty and scroll does not appear. Then i add content in $(‘#content.mCSB_container’) and in some moment scroll appears. Can i listen this event?
1) Yes, this is normal behavior. To re-initialize a scrollbar with different options, most of the times you’ll need to destroy the scrollbar before calling mCustomScrollbar function again on the same element. For instance:
$('#content').mCustomScrollbar(); $('#content').mCustomScrollbar("destroy"); $('#content').mCustomScrollbar({callbacks: { onScroll: function() { console.log('scroll') } }})
2) There’s no user available callback within the plugin script to check if the scrollbar is visible/active or not. This said, you could get your element’s state as when no scrollbar is needed, it gets the class:
mCS_no_scrollbar
. This class won’t be present when content is long enough to require the scrollbar.Ok, thank you very much!
Sorry, I’m posted my questons twice
Is there a way to use a theme without javascript?
Yes, by using the data-mcs-theme attribute in your html. For example:
<div data-mcs-theme="inset">...</div>
Thanks. Now there’s another problem.
I have a main container and a nested container with only horizontal scrollbar.
<div class="pmain mCustomScrollbar" data-mcs-theme="dark"> <div class="pvert" data-mcs-axis="x" data-mcs-theme="dark">
Problem is that the horizontal scrollbar (for nested container) only shows if I add the following code (taken from a demo).
$(".pvert").mCustomScrollbar({ advanced:{autoExpandHorizontalScroll:true}});
The horizontal custom scrollbar works the same way CSS overflow-x:auto works, meaning your (inner) content should be wider than its container (the element with the scrollbar).
For instance, when you have left-floated elements directly inside a div, those will stack horizontally only until they’ve reached the div’s right side. The next floated element(s) will form a “new line”.
To make your content wider, you’d need to wrap your floated elements in another div which must have a higher width value than its container. For example:
<div class="the-div-with-the-scrollbar" style="width:400px;"> <div class="the-wrapper-div" style="width:800px;"> <div class="floated-div">...</div> <div class="floated-div">...</div> <div class="floated-div">...</div> </div> </div>
The plugin, via the autoExpandHorizontalScroll option parameter provides a way to add the wrapper (in the example above: .the-wrapper-div) automatically, in order to expand its width according to its contents without the need for you to add a fixed width.
So you either need to use this option, or add such a div manually in your html.
Hope this helps
Hi,
When I refresh page first I see “standard” browser grey scrollbar (it means – about half second) and after that I see jquery scroll bar.
Where is the reason?
This happens because the plugin is initialized when page is fully loaded, e.g.:
$(window).load(function(){ $(".content").mCustomScrollbar(); });
So while the page is loading, the default browser scrollbar appears normally and when all content is loaded, it’s replaced by the custom scrollbar. This happens on overflow:auto elements.
There are 2 ways of dealing with this:
1. Initialize the plugin on DOM ready:
$(document).ready(function(){ $(".content").mCustomScrollbar(); });
2. Set your element’s CSS overflow property to hidden:
.content{ overflow:hidden; }
Second option works. Thanks!
Hi..
How to set scroll position to bottom when content update dynamically ?
Thanks.
not any option… that time only default scroll will work not any jquery…
like on popup.
or you can put that updated div in left or right position -9999% something .
not put that updated div as display:none.
Each time the content is updated, call plaugin’s scrollTo method, e.g.:
$(selector).mCustomScrollbar("scrollTo","bottom");
Hi malihu, I just started using your plugin on my startup website and I’m loving it!
However I’m encountering a little issue. Let me explain:
1. As stated on the instructions I’m initializing the plugin calling it in the header of my page and assigning the required tag to the body as follows:
<body class="full-page mCustomScrollbar _mCS_3 mCS-autoHide" style="position: relative; overflow: visible;">
2. The scrollbar works flawlessly. Now what I need is the body to scroll to a specified div when a button is clicked on the page. I’m trying to do it by calling the specific scrollTo method but it is not working. Here is the function I’m using:
jQuery("#next_arr").click(function() { jQuery(this).toggleClass('rotate'); jQuery( "#discover_container").slideToggle( "slow" ); jQuery( "#arr_container").slideToggle( "slow" ); jQuery('body').mCustomScrollbar("scrollTo","bottom"); });
May you help me solving this issue? Thanks so much in advance.
Hi,
When you say it’s not working, you mean it doesn’t scroll to the “correct” div or it doesn’t scroll at all?
If it does scroll maybe you need to call the scrollTo method after animations are complete:
jQuery("#arr_container").slideToggle("slow", function(){ jQuery('body').mCustomScrollbar("scrollTo","bottom"); });
If it doesn’t scroll at all, check if you get any console errors when opening your page with browser\s developer tools (other errors might prevent the script from executing).
Hi malihu,
Thanks fro the rapid response. However the issue seems not solved. I tried with the code provided by you but it doesn’t go. The problem is that the body doesn’t scroll at all. I checked the console with the Chrome inspector but there are no errors. Any idea why the scroll is not working? All the other jQuery animations are working except the scroll.
I’m assuming that the #discover_container and #arr_container elements hold content that changes the body length when toggled.
Since body has a custom scrollbar attached, each time those elements are toggled, the script needs to update the scrollbar according to content length. While the script updates the scrollbar, it’ll interrupt any scrollTo method calls (this is by design).
It seems that this is the reason your scrollTo method call doesn’t work. The script hasn’t finish updating the scrollbar according to content’s length (which is changing with the toggled elements) and so it prevents the scroll-to bottom animation.
Since both your slideToggle animation have the same duration (‘slow’) the code I posted should work, but maybe the ‘rotate’ class toggle triggers another CSS3 animation that’s longer than the others.
In any case, the goal is the same. Call the scrollTo method after all animations are fully done. You could probably add a timeout and do some tests changing the milliseconds value to see when it’ll work. For example:
setTimeout(function(){ jQuery('body').mCustomScrollbar("scrollTo","bottom"); },700);
Thank you so much man!
Setting the Timeout to 600 solved the issue and now everything is working flawlessly!
Check out my website SportAround.me and look how well your scrollbars fits on it! 😉
Looks great 🙂 Good work!
The plugin is fantastic .Thanks, I’m using it in many projects
Maybe I missed the documentation but is there a way to enable scrolling when implementing drag/droping within the div which mCustomScrollbar is applied to? Utilizing Jquery sortable and would like to be able to drag and auto scroll when I drag past the top or bottom of the scroll area.
Cheers
this is a quick hack I put together although it needs work, right now if I drag over the area it will start scrolling to either the top or bottom determined if I drag past the top or bottom of the area…
// Hacking the List
document.onmousedown = docOnMousedown;
document.onmouseup = docOnMouseup;
function docOnMousedown(e){
mouseIsDown = true;
}
function docOnMouseup(e){
mouseIsDown = false;
}
$(“#dynamic-list “).mouseleave(function(e) { //Dynamic list is my scrolling windows parent div
var window = $(this);
var bottom = window.offset().top + window.outerHeight();
var top = 0;
if(e.pageY >= top && mouseIsDown == true){ // dragged past top of parent window
$(‘#dynamic-list’).mCustomScrollbar(“scrollTo”,”top”,{
scrollInertia:2000
});
}
if(e.pageY >= bottom && mouseIsDown == true){ // dragged past bottom of parent window
$(‘#dynamic-list’).mCustomScrollbar(“scrollTo”,”bottom”,{
scrollInertia:2000
});
}
});
// Hacking the List
any ideas? or am I overthinking this….
I’ve put a jquery ui sortable example in the download archive. You can see it here: http://manos.malihu.gr/repository/custom-scrollbar/demo/examples/jquery_ui_sortable_example.html
Source: https://github.com/malihu/malihu-custom-scrollbar-plugin/blob/master/examples/jquery_ui_sortable_example.html