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 🙂
Hi,
I am using mCustomScrollbar in the redesign of a website. The vertical works perfect and callbacks are really useful and save time and lines of code. The problem is with the horizontal scroll. I red all comments, took look at links provided, try many of those codes, but still can’t make the horizontal scroll work. You can see website here (work in progress) : FBR New Design
Hope there will be some solution.
Kind regards
Hello,
You horizontal scrollbar (on .page1_scroller_in element) does work.
It’s just that your content is not wide enough to require a scrollbar. If you add more content or set its width to something like 15% you’ll see the scrollbar.
I added some more text and it really works, but styles got weird. Thanks for your help, I will look at those styles now.
It looks like dimensions are getting all wrong (similar to the problem of other Ivan on this page)
You must either give your paragraphs a fixed width, e.g. 200px (not percentage) or disable
autoExpandHorizontalScroll
by setting it tofalse
and wrap the paragraphs with a fixed-sized div (just as you would with the native browser scrollbar).Hi,
I am using the option “alwaysShowScrollbar: 1”. This allows the scroll bar to fixed visible even the number of rows are low. But it doesnot shows the dragger icons. what we need to do in this case?
P.S: I need a disabled mode dragger icons.
Thx,
Set
alwaysShowScrollbar: 2
. See alwaysShowScrollbar option in Configuration section for more info. These settings ususally work well with a fixed sized scrollbar dragger (e.g.autoDraggerLength: false
).But it does not displaying in a hidden mode. What i need is to have a disabled dragger and disabled icon if my grid does not have enough rows.
I checked in the configuration. But didn’t get an expected solution.
Any idea?
Setting
alwaysShowScrollbar
value to2
should work. I’ll need to see your page to help more. Can you send me a link?Hello, I have a panel which has to have a variable height. The panel/wrapper has height:auto; and max-height:100%; so it stays as the inside content or 100% of the viewport height if content is higher.
You can see my problem here(the panel does not resize if resized to smaller and than back):
http://www.magicmarinac.hr/razno/imagis/img.jpg
Live example:
http://www.magicmarinac.hr/razno/imagis/code.html
I can’t get the fiddle working with your plugin, don’t know what i am doing wrong 🙂
http://jsfiddle.net/ahdy2r45/
Is it possible with height and max-height like that because it works without the plugin? Any info would be appreciated .
Tnx
Hello,
At the moment, the script cannot replicate the exact behavior of browser’s native scrollbar when CSS height is set to “auto” and max-height is set to percentage.
This said, you can accomplish the same behavior with a tiny jquery script.
Just give your element height: auto; (without specifying a max-height) and add the following script to your document or .js (after you’ve called mCustomScrollbar function on your selector):
<script> (function($){ $(window).bind("load resize",function(){ $(selector).css("max-height",$(window).height()).mCustomScrollbar("update"); }); })(jQuery); </script>
Malihu, great help, it works like i wanted. Thank you! Best Regards!
There are a couple of bugs in this. First of all, the code assumes that $ is the same as jQuery, which is not always a valid assumption. Easy fix, tho. Change line 39 of jQuery.mCustomScrollbar.js to:
;(function(window,document,$,undefined){
And the last line to:
}))}(window,document,jQuery));
Also, the code doesn’t correctly detect if a user grabs the scrollbar and scrolls down from the top, then back up again. onTotalScrollBack isn’t called (and vice-versa for scrolling up, then down, at the bottom of the scroller). There’s a fairly simple fix, though. Change the onUpdate function starting on line 1915 to this:
var scrollDir; if(options.callbacks && options.onUpdate){ /* callbacks: whileScrolling */ if(_cb("whileScrolling")){ scrollDir = scrollTo[0] + scrollTo[1]; if ((0 == scrollDir) && ((scrollTo[0] < 0) || (scrollTo[1] < 0))) { scrollDir = -1; } else { scrollDir = (scrollDir < 0) ? -1 : ((scrollDir > 0) ? 1 : 0); } _mcs(); if ((!d.cbOffsets[0] && (1 == scrollDir)) || (!d.cbOffsets[1] && (-1 == scrollDir))) { d.cbOffsets = _cbOffsets(); } o.callbacks.whileScrolling.call(el[0]); } }
This detects if you’re scrolling *away* from the top or bottom, and then resets the flag which controls whether the scroll up or down callback, respectively, is allowed to fire.
Minor change to the onUpdate function above:
var scrollDir; if(options.callbacks && options.onUpdate){ /* callbacks: whileScrolling */ if(_cb("whileScrolling")){ scrollDir = scrollTo[0] + scrollTo[1]; if ((0 == scrollDir) && ((scrollTo[0] < 0) || (scrollTo[1] < 0))) { scrollDir = -1; } else { scrollDir = (scrollDir < 0) ? -1 : ((scrollDir > 0) ? 1 : 0); } _mcs(); if ((!d.cbOffsets[0] && (1 == scrollDir) && (scrollTo[1]>totalScrollBackOffset)) || (!d.cbOffsets[1] && (-1 == scrollDir) && (scrollTo[1]<limit[1]-totalScrollOffset))) { d.cbOffsets = _cbOffsets(); } o.callbacks.whileScrolling.call(el[0]); } }
The same functionality can be achieved if you don’t set alwaysTriggerOffsets to false (in callbacks_example.html is set to true):
callbacks:{ alwaysTriggerOffsets: true }
Thanks for the feedback!
The missing
$
andjQuery
in the function expression is a (known) issue (a wrong pull request on github for requireJS support in version 3.0.3). This part of the code will be fully updated on the next version (hopefully by this week).I’ll also try to test the code you provided and implement it on next version (3.0.5). As it is now, the onTotalScroll and onTotalScrollBack callbacks are triggered only when a scroll event first completes (e.g. when dragging the scrollbar to a point, scrolling is stopped and then dragging it back again)– see the comment above (http://manos.malihu.gr/jquery-custom-content-scroller/comment-page-54/#comment-18184).trackpad gestures don’t work on pages using the horizontal scrollbar within an iframe (the vertical scrollbar works correctly)
Any known fix for this?
This actually happens only if you declare axis as “yx” , when using “x” only the horizontal scroll works fine.
This only happens when the axis is declared as “yx” . Using ‘x’ only, fixes the issue. Basically it seems that a single container cannot handle both x and y movements at the same time.
hello,
awesome plugin, but i can’t acheive what i need.
I would like to have 2 buttons (up and down) and be able to scroll on click.
i’ve try :
and :
$("#down").click(function() { $("#wrapper_news").mCustomScrollbar("scrollTo",200); }); $("#up").click(function() { $("#wrapper_news").mCustomScrollbar("scrollTo",-200); });
but unfortunately this doesn’t work…
any help would be much appreciated !!
Thanks a lot
Hi,
Assuming everything else in your implementation is correct, you probably need something like this:
$("#down").click(function() { $("#wrapper_news").mCustomScrollbar("scrollTo","-=200"); }); $("#up").click(function() { $("#wrapper_news").mCustomScrollbar("scrollTo","+=200"); });
it works !
awesome, thank you so much for your quick answer !
Hello Malihu,
I experienced lagging problem when performing “scrollTo” function with a lot of content.
And i try to integrate your _tweenTo by replacing it with velocity.js (http://julian.com/research/velocity/) .velocity function which is the replacement of jquery Animate function. Which i hope will solve the lagging problem.
can you guide me on how to integrate that?
or you can give me advice on to make it not lagging when performing “scrollTo” function on lot of div content which contain images.
Hello,
The lagging problem may happen for any number of reasons. Does it happen on all browsers? Firefox animations for example are always more laggy than Chrome/IE.
Do you use a lot of css box-shadows and border-radius in your content? These usually affect performance. Have you tried toggling some css rules and see it performance gets better? Do you let browser scale down your images?
I don’t think velocity.js will help as it is uses the same principles with _tweenTo.
velocity.js is a vanilla javascript animation library. _tweenTo function is a vanilla javascript animation tween (optimized for performance). I created the custom tween inspired by GSAP tween library (which out-performs all other libs) and integrated it within the plugin script.
My point is that if you experience lag with certain content with the _tweenTo function, you will experience the same lag with velocity.js, zepto, GSAP etc. (I’ve done extensive tests on this).
In any case, I can’t really provide a guide on replacing _tweenTo with velocity.js as the tween is tightly integrated with the rest of the script.
Thank you for your reply Malihu,
ok then, let me search on those css problems first.
Thanks a lot !
Hi!
I’m using horizontal customscrollbar and it works fine on firefox, but no way to get it working on chrome
the code is
<script src="http://www.unioneimpreseitaliane.it/web/customscrollbar/js/minified/jquery-2.1.0.min.js"></script> <script src="http://www.unioneimpreseitaliane.it/web/customscrollbar/js/minified/jquery-ui-1.10.4.min.js"></script> <script src="http://www.unioneimpreseitaliane.it/web/customscrollbar/js/minified/jquery.mousewheel.min.js"></script> <link rel="stylesheet" href="http://www.unioneimpreseitaliane.it/web/customscrollbar/jquery.mCustomScrollbar.css" /> <script src="http://www.unioneimpreseitaliane.it/web/customscrollbar/jquery.mCustomScrollbar.concat.min.js"></script> <script> (function($){ $(window).load(function(){ //news box $("#rpwe_widget-2").mCustomScrollbar({ theme:"dark-thick" }); $(".post").mCustomScrollbar({ theme:"dark-thick" }); /* //scroll orizzontale totale $("#main").mCustomScrollbar({ axis:"x" // horizontal scrollbar }); you can test it here http://www.unioneimpreseitaliane.it/web as you can see, the main div is hidden in chrome what's wrong with that? thanks for checking this! Navigation $(".menu a").click(function(){ var myid= $(this).attr("href"); $("#main").mCustomScrollbar("scrollTo","" + myid + ""); });*/ }); })(jQuery); </script> <script> $(function(){ $(window).load(function(){ $("#main").mCustomScrollbar({ axis:"x", horizontalScroll:true, scrollInertia:1100, advanced:{ autoExpandHorizontalScroll:true }, /*, callbacks:{ onScroll:function() { alert("scrolled..."); } }, scrollButtons:{ enable:true }*/ }); /* Navigation */ $(".menu_sidebar a").click(function(){ axis:"x"; var myid= $(this).attr("href"); $(".menu_sidebar a").removeClass('selected'); $(this).addClass('selected'); $("#main").mCustomScrollbar("scrollTo","" + myid + ""); }); }); })(jQuery); </script>
You probably need to give #main-sidebar-container a height value:
#main-sidebar-container{ height:100%; }
omg!
you made my day!
thanks a million! 😀
you are magic
Hi, I’m sorry to trouble you many times,
I have solved many problems under your earnest help, thanks very much, now also another important question troubles me, we use cometd , so when a new message arrives, the server will push it to several pages of a same user, eg:
I open three windows in the same brower, and now I choose the first , when someone sends me a new message, all of these windows will receive a new message to update the record use the below code
_chatScroll.mCustomScrollbar('scrollTo', 'bottom', {scrollInertia:300, timeout:500});
but only the page that I have choosed can scrollTo normally , the other window’s scrollTo method can not work,
<div dir="ltr" style="position: relative; top: -1011770px; left: 0px;" class="mCSB_container" id="mCSB_3_container">
I have tried to increase the timeout ,but not work,
I can’t understand why only the choosed page can work, but others will not, this question troubles me long time.
Does it happen in all browsers?
From my experience with similar web apps a solution might be to manually call the update method and/or set
scrollInertia
value to 0 (zero).For example, disable plugin’s auto-update functionality on plugin initialization:
_chatScroll.mCustomScrollbar({ advanced:{ updateOnContentResize:false } });
and then, before your scrollTo method call, call the update method manually:
_chatScroll.mCustomScrollbar('update').mCustomScrollbar('scrollTo', 'bottom', {scrollInertia:0, timeout:0});
I have solved my problem which is very important to me with your solution , and it obviously works, you are so great, thanks very much.
Also welcome to china.
I have embedded the custom scroll bar within the simple horizontal jquery ui tabbed panel plug-in (http://jqueryui.com/tabs/) in order to use the scroll bar inside each of the panels.
I have three tabs (#tabs-1, #tabs-2, #tabs-3) with simple lorem ipsum in each.
Using
<script> (function($){ $(window).load(function(){ $("#tabs-1, #tabs-2, #tabs-3").mCustomScrollbar(); }); })(jQuery); </script>
enables the custom scroll bar to work on the first tab but not the other two. There are no differences among the tabs, and I’ve tried $(document).load, enable: true, and various placement of the scripts in the WordPress pages.
Obviously I don’t now what I’m doing. Help would be much appreciated.
Have you seen and view the source of the jquery_ui_tabs_example.html?
It’s a demo of jQuery UI tabs with custom scrollbar(s) and you can see it online here:
http://manos.malihu.gr/repository/custom-scrollbar/demo/examples/jquery_ui_tabs_example.html
The demo contains 2 examples. One with a different scrollbar for each tab and one with a single scrollbar (placed outside of the tabs container) for all tabs.
You probably need to call mCustomScrollbar function on each tab panel upon tabs creation using jQuery UI tabs API. An example from the demo:
$(tabs-container-element).tabs({ create:function(e,ui){ $(".ui-tabs-panel").mCustomScrollbar({ setHeight:300 // you'll need to give a height to your tabs container }); } });
No, I hadn’t seen that demo page. But it’s exactly what I was looking for. Many thanks.
Hello.
How to I use a theme? I have no idea how to get it to work.
Thank you!
Set the theme you want in the theme option parameter when you invoke the plugin:
$(".content").mCustomScrollbar({ theme:"theme-name" });
You can see all available ready-to-use themes here:
http://manos.malihu.gr/repository/custom-scrollbar/demo/examples/scrollbar_themes_demo.html
Hi,
I wan to know how can I hide the scrollbar when use the scrollTo method ?
$('#scrollContent').mCustomScrollbar('scrollTo','bottom');
and I use the above code to scrollTo the bottom everytime when I open the window,
callbacks : { onScroll : function(){ // dosomething }, onScrollOffset:40
use this code, I can only call my define function which has scroller, how to do when no scroller with it?
You cannot trigger the onScroll callback without scrolling (which is the same as without a scrollbar). What you need to use is probably the onOverflowYNone callback which is triggered when content becomes short enough and vertical scrollbar is removed (see “Configuration” section for more info).
Hello, I have a problem.
When I click in scrollbar, the inertia stay hold and scroll with my mouse moves.
Can you help me?
Hello,
Can you describe a bit more the problem? Can you send me a link?
Okay, I’ll try explain…
When the content is open, I click in scrollbar, then I can scroll up and scroll down, that’s right, but when I move the mouse outside of content, the content keeps scrolling, without the click in scrollbar.
The page is not published, so i have no link. Sorry.
When the scrollbar keeps moving (as if you where dragging it) even when you have released the mouse anywhere on your document, it usually means that another script is blocking mouse events bubbling up the DOM.
Unfortunately, there’s no way to tell if there’s a simple solution or how to solve such issues unless I see your page/code.
You’re right! Is a conflict with the select2. Looking around I found same problem, but i tried the solution of #comment-18068 and just don’t works!
Same version and same conflict.
In such case you may need to add the select2 mask as an extra selector:
add(mCSB_dragger).add($this).add($(".select2-drop-mask"))
Depending on where select2 appends its mask element, the above might work.
Can AnyOne Help Me plz need to create Horizontal Scrollbar but unable to facing lots of Problems give you give me sample with HTML and Js
Thank you in advance for help
Hi,
The demo here: http://manos.malihu.gr/repository/custom-scrollbar/demo/examples/scroll_buttons_and_snap_scrolling_examples.html (included in the download archive) is a horizontal scrollbar.
Basically you create your horizontal markup to work with browser’s native scrollbar and then call mCustomScrollbar function on it. If your content overflows your container horizontally it will work.
I also have another problem, when I switch contacts most quickly in the webIm system, the scrollbar of the final contact’s chat panel can not scroll to the bottom, the code:
_chatScroll.mCustomScrollbar(‘update’).mCustomScrollbar(‘scrollTo’,’bottom’, {scrollInertia:300});
but also work normally when do it slower. we use jquery cometd to in this system, looking forward to your reply.
If a scroll-to event is not working, it probably means that the plugin script is still updating the scrollbar(s) according to (newly loaded) content.
This is roughly how the script works:
When you add new content to an element which has scrollbar(s), the plugin script automatically updates all scrollbar functionality according to new content (this can be set true or false via the
advanced:{ updateOnContentResize }
option). Now, while the script is updating, it will stop any scrollTo method events cause scroll-to position will be wrong.The scrollTo method event has a default timeout of 60 milliseconds to compensate for the auto-update function of the script. You can change this timeout (in version 3.0.4) for any scrollTo method call like this:
$(selector).mCustomScrollbar("scrollTo","bottom",{ timeout: 300 });
When you switch contacts very fast, the scroll-to event is stopped because the script is still updating the scrollbar, so you may need to increase the timeout option parameter as above.
hi,
thanks for your reply, the parameter of timeout really functioned, but not very exactly, how to do that I can know when the updating scripts is completely finished, so I can use the scripts to scroll the bar to the bottom?
The auto-update function of the script has an interval of 60 milliseconds, so this the least amount you need to make sure that scrollbar is up-to-date with the content.
What you need to know is when new content is fully loaded, which is handled by your script(s). Since you’re using the latest plugin version, you don’t need to call the update method manually.
Just make sure that content is fully loaded before calling scrollTo method.
$('.recent').live('click', function(){ //如果点击的是当前对话好友 则返回 if($(this).hasClass('imCurrent')){ return; } var $input = $(this).find('input'); _cometd.publish('/service/chat/read', { memberId : _user.memberId, toMemberId : $input.attr('toMemberId'), relationId : $input.attr('relationId') }); }); _cometd.subscribe('/service/chat/read', _self.receiveReadMessage);// 订阅读取消息的频道 this.receiveReadMessage = function(message){ _userChat = {};//重置标识时间 var $input = getInputByToMemberId(message.data.user.memberId); //移除其他样式 标志当前为正在会话的好友 _currentChat = $input.parent('li'); _currentChat.addClass('imCurrent').siblings('li').removeClass('imCurrent'); //置空消息数 _self.updateMessage($input.attr('relationId'), true); //提示消息数 $('#currentChat').text($input.attr('toMemberName').substring(0,3)+'…-对话中'); _initFriendContents(message.data.contents, message.data.relationId, message.data.isExist);//init the chat record of friend _initFriendMessage(message.data.user);//初始化好友资料 _chatScroll.mCustomScrollbar('scrollTo','bottom', {scrollInertia:300, timeout:500}); }; function _initFriendContents(arr, relationId, isExist){ _chatRecord.html('');//先清空 后追加 if(arr && arr.length>0){ for(var i=arr.length-1; i>=0; i--){ var item = arr[i]; var date = _isChatTimeChanged(item.formateDate_all); if(i==arr.length-1){//初始化第一条聊天记录的时间 _userChat._lastMoreRecordsTime = item.formateDate_all; } if(item.sendId == _user.memberId){ //自己发送的 _addSelfContent(_chatRecord, item.sendName, item.content, true, date); }else{ //好友发送的 _addFriendContent(_chatRecord, item.sendName, item.content, true, date); } } _addChatMoreBtn(relationId, isExist);//是否有更多聊天记录 } }
there are the main code, first, subscribe a channel, and when click the friend in friend list, it will publish the channel use ajax, then call the callback function to change the chat record in chat window, and update the scrollbar to the bottom, how can I know when the content is fully finished? thanks
hi,malihu,I have a problem, recently, we are developing a webIM system ,so it will receive a same message in the diffrent pages, and also all of it shoud update the scroll to the bottom. but now ,it just work nomarlly in the current page and in other pages it does’t scroll to the bottom,sometimes ,the page turn into empty, when you scroll the scrollbar , it will work normally. can you help me?
Which plugin version are you using? Do you call the methods on window load (after all content is loaded)? Do you call the scrollTo method before making sure content has loaded? See also the reply above as it might help.
I use version 3.0.3 , when the page initialize,I use code
$('div[id*=scrollBar][id!=chat-scrollBar]').mCustomScrollbar({ theme : 'minimal-dark', mouseWheel : { preventDefault : true }, scrollButtons : { enable : true } });
now , I update the version to 3.0.4 , and use the below code to update the scrollbar:
_chatScroll.mCustomScrollbar('update').mCustomScrollbar('scrollTo','bottom', {scrollInertia:300, timeout:300});
because the same chat window is opened in diffrent tabs or browsers, when I switch the contacts (or someone send me a new message), the current page’s scroll can work well, but other pages also can’t scroll to bottom to see new message, maybe I should increase the timeout greater.
You can skip the update method call:
_chatScroll.mCustomScrollbar('scrollTo','bottom', {scrollInertia:300, timeout:300});
I don’t really know how your web app works, but maybe you need to call the scrollTo when switching tabs(?)
Hi.
I want to say that what you have done and shared with us is simply genius and freaking generous!
I’m a noob to all this java stuff but I get by. I’m working on a non profit site for my gaming clan.
Your code replaces my content div with the following:
…
Yet the scroll bar does not show and what interests me is the following, mCS_no_scrollbar.
Is there a setting some where?
Any help will be appreciated!
Weird the code did not show up.
<div id="contentMiddleData" class="mCustomScrollbar _mCS_1 mCS_no_scrollbar"><div id="mCSB_1_container" class="mCSB_container mCS_y_hidden mCS_no_scrollbar_y" style="position: relative; top: 0px; left: 0px;" dir="ltr">…</div><div id="mCSB_1_scrollbar_vertical" class="mCSB_scrollTools mCSB_1_scrollbar mCS-light mCSB_scrollTools_vertical" style="display: none;">…</div>
.mCS_no_scrollbar class means that the content is shorter than its container, so no scrollbar is needed. Does your element have a height set? You need to give your element a height (or max-height) value (either in CSS or via the setHeight option parameter).
Thank you.
I set a height to the div which has class .mCustomScrollbar and it works. Youpi!
You’re welcome.
Great avatar 🙂
Is there an option/easy way I can make a scrollable content area click-and-draggable to scroll? I have a large image I’d like to pan around in a scrolling container, I can do it if the user has a mousewheel but not if they don’t…
There’s no such function implemented into plugin script. If the user is on a touch-enabled device he can scroll/pan by touch-swiping the content.
hi, I’m trying to use the scrollTo bottom, but it doesn’t work, when I use it the scroll doesn’t work.. like if you haven’t apply the plugin, loss the format, can you help?
Are loading new content to your element with the scrollbar while trying to trigger scroll-to? Do you get any console errors? Can you send me a link so I can check it online?
hi, I couldn’t see any javascript error.. and I’m trying with a static content but later I’ll need with a dynamic content, like a history message and need to scroll bottom when select an item. this is the url you can see the static html
http://sitio2.bitworks.com.sv/scroll/index.html
Before calling plugin methods, you need to initialize the plugin.
You’ve called mCustomScrollbar function only on your first div (.content). You need to also call it on .content2
$(".content, .content2").mCustomScrollbar(); $(".content2").mCustomScrollbar("scrollTo", "bottom");
thanks
hi Malihu, I found a solutions for my problem.. I used a setTimeout after call mCustomScrollbar() function, then put a new mCustomScrollbar(“scrollTo”,”bottom”) to scroll to bottom and works
Hi,
I have a problem. I have a header() element which holds numerous tabs(link buttons). I have applied this scroll bar. I have many rows(of link buttons) in that header . Whenever i scroll , it always scrolls to top or bottom row and never to any intermediate rows(rows contains link buttons).
Can you please help me to solve this problem.
Maybe you need to apply CSS position rule to your rows? I’m just guessing here and can’t really help unless I see your page/file.
Hello,
I just need to know if there is any example code of the “auto-scroll” on horizontal images? Yes! there is an example of it on the vertical version. I tried changing some elements on that code from “auto-scrolling-to-bottom” to “auto-scrolling-to-right” but doesn’t seem to work.
Hello,
If you’re using the latest version (3.0.4), there’s a better way of doing it:
var content=$("#content-1"), //element selector loopDuration=14000, //loop duration e.g. 7s to right, 7s to left totalLoops=2; //number of loops: 0 for infinite loops content.mCustomScrollbar({ axis:"x", advanced:{ autoExpandHorizontalScroll:true }, scrollButtons:{enable:true}, callbacks:{ onOverflowX:function(){ _autoScroll("right"); totalLoops-- }, onTotalScroll:function(){ if($(this).data("mCS").trigger==="external"){ _autoScroll("left"); } }, onTotalScrollBack:function(){ if($(this).data("mCS").trigger==="external" && totalLoops){ _autoScroll("right"); totalLoops-- } } } }); function _autoScroll(to){ content.mCustomScrollbar("scrollTo",to,{scrollInertia:loopDuration/2,easing:"easeInOutSmooth"}); }
Hi. I am using your plugin and it’s fine. But I can’t to adjust smooth scrolling. there is “jumping” to slide effect. Please help
$(“.slider”).mCustomScrollbar({
axis:”x”,
mouseWheel:{
enable: false
},
scrollButtons:{
enable: true,
scrollAmount: 30
},
});
I’ll need more info on the problem…
Is the scrolling not smooth enough?
Does the same happen when you view the demo and examples? If the scrolling is not smooth enough it’s probably due to content (e.g. having too many css shadows etc.) and/or browser engine (e.g. Firefox js animations are worse than Chrome, IE etc.).
Can you send me link?
The scrollto element isn’t working on touch devices would there be a fix for this?
I am initiating it on page load then adding this when the content area is populated with images
jQuery(“.gallery-inner”).mCustomScrollbar({
axis:”x”,
theme:”inset-dark”,
advanced:{
autoExpandHorizontalScroll:true
},
scrollButtons:{
enable:true,
scrollType:stepped
},
keyboard:{scrollType:”stepped”},
snapAmount:amount,
mouseWheel:{scrollAmount:amount}
});
jQuery(“.gallery-inner”).imagesLoaded( function() {
jQuery(“.gallery-inner”).mCustomScrollbar(“update”);
});
Seems you’re using the update method instead of scrollTo. You probably need to change:
jQuery(".gallery-inner").mCustomScrollbar("update");
to:
jQuery(".gallery-inner").mCustomScrollbar("scrollTo", "#id");
HI
how to control mouse wheel scrolling speed , i need to reduce the speed .
this is my jquery
$(“.content”).mCustomScrollbar(“scrollTo”,”bottom”,
{
scrollInertia: 10000000,
mouseWheel:{
scrollAmount: 1000000000
}
}
);
Hi,
The code you posted is calling plugin’s scrollTo method which manually scrolls content to a specific location (this method does not have any mouse-wheel option parameter).
You should use/set the mouseWheel option on plugin initialization:
$(“.content”).mCustomScrollbar({ scrollInertia: 950, mouseWheel:{ scrollAmount: 100 } });
Note that scrollInertia value is milliseconds and scrollAmount value is pixels.
Thanks a lot
Hi Manos,
thank you for your great plugin, looks great!
I am having trouble with the mousewheel / trackpad scrolling amounts and can´t find a way to even them out. Problem is, using an apple trackpad to scroll the content makes it scroll much to fast, so I change scrollAmount to something like 100, which makes it feel alright, but then scrolling with a mousewheel using my windows pc is going much to slowly. I was folling around with the deltaFactor and normalizeDelta values, but couldn´t find something that really makes both ways of scrolling feel nice. Any suggestions?
Thanks and kind regards,
quenn
Are you using the latest plugin version? I added a fix for this in version 3.0.4
Thanks for the immediate support!
I am using version 3.1.11 – any other ideas?
No, I meant which custom scrollbar version you’re running (not mousewheel). The latest is 3.0.4. If you’re running an older version, re-download the plugin as the latest version contains the fix.
thank you very much, that did it!
great plugin and great support, sent you a donation, hope you can keep up the good work.
Thanks a lot for the donation 🙂
I’ll do my best!
Hi. Great plugin! I have a question. It does not seem to work when you use the search function in your browser. Or when you add in-page anchor points, eg. . This is a bug, right?
In-page URL anchors work only with browser’s native scrollbar, but you can do the same (and much more) via plugin’s scrollTo method (see plugins methods).
Browser’s search function is an internal mechanism and cannot be replicated (at least for now).
Ok. Thanks a lot for your feedback!
HI,
Right now I am working on responsive layout for my portfolio where I am using custom5 the horizontal scroll bar.
Could you please tell how to configure custom 5 horizontal scroll bar to vertical. When I switch over small device (Mobile).
Please give me some advice.
Regard
Mahadevan
Hi,
The best thing you can do in such cases is applying both scrollbars (vertical and horizontal) on your element and simply change its width/height and your contents float property via your CSS media queries.
For example, assuming your HTML is like this (using paragraphs for simplicity):
<div id="content-5"> <p>Element</p> <p>Element</p> <p>Element</p> <p>Element</p> <p>Element</p> <!-- and so on... --> </div>
Apply both scrollbars along with the other options:
$("#content-5").mCustomScrollbar({ axis:"yx", theme:"dark-thin", autoExpandScrollbar:true, advanced:{autoExpandHorizontalScroll:true} });
In your CSS you can do:
/* mobile first the following will apply when viewport width is less than 1024px */ #content-5{ width: 260px; height: 400px; } #content-5 p{ width: 200px; height: 120px; } /* the following will apply when viewport width is 1024px or greater */ @media only screen and (min-width: 1024px){ #content-5{ width: 80%; height: 170px; } #content-5 p{ float: left; } }
So what you do, is change your element’s width/height and make your inner contents float left.
This is fairly simple but the tricky part is how to make mouse-wheel scroll the “correct” axis according to your element’s CSS (after all you’d want the mouse-wheel to scroll x-axis when the horizontal scrollbar is displayed and vice-versa).
To do this, you can use plugin’s onOverflowY and onOverflowX callbacks and change mouse-wheel axis option on-the-fly:
$("#content-5").mCustomScrollbar({ axis:"yx", theme:"dark-thin", autoExpandScrollbar:true, advanced:{autoExpandHorizontalScroll:true}, callbacks:{ onOverflowY:function(){ var opt=$(this).data("mCS").opt; if(opt.mouseWheel.axis!=="y"){ opt.mouseWheel.axis="y"; } }, onOverflowX:function(){ var opt=$(this).data("mCS").opt; if(opt.mouseWheel.axis!=="x"){ opt.mouseWheel.axis="x"; } }, } });
I have a working example that you’d probably want to view/get here:
http://manos.malihu.gr/repository/custom-scrollbar/tests/yx-axis-with-media-queries/
Hi,
Thanks for the reply malihu.
I will try it.
Regards
Mahadevan
Hi,
When i try to add the axis the entire div is missing 🙂
Here is the code
$(“#content-5”).mCustomScrollbar({
axis: “yx”,
theme: “dark-thin”,
autoExpandScrollbar: true,
advanced: { autoExpandHorizontalScroll: true },
callbacks: {
onOverflowY: function () {
var opt = $(this).data(“mCS”).opt;
if (opt.mouseWheel.axis !== “y”) {
opt.mouseWheel.axis = “y”;
}
},
onOverflowX: function () {
var opt = $(this).data(“mCS”).opt;
if (opt.mouseWheel.axis !== “x”) {
opt.mouseWheel.axis = “x”;
}
},
}
});
Kindly suggest
Regards
Mahadevan
Did you apply/change the CSS I posted above?
Hi sorry
It was working fine. But when I change p tag to div it was not at all working
Element
Element
Element
Element
Element
Kindly suggest.
Regards
Mahadevan
Have you changed
#content-5 p
to#content-5 div.class-name
in the CSS?Your divs need width/height set and a class-name to target them properly.
Hello Malihu,
seems like your scrollTo with percentage value is not exactly move to that percentage.
In demo files: scrollTo_demo.html
I log the left percentage for the scroll x demo, it shows: 13% instead of 10%
$(".demo-x").mCustomScrollbar({ axis:"x", advanced:{autoExpandHorizontalScroll:true}, callbacks:{ whileScrolling:function(){ console.log(this.mcs.leftPct); }, } });
If i try 50% it goes to 64%
How to fix this to be exactly for that percentage?
Thanks before for the great plugins.
Hello,
Please note that those 2 values (leftPct and scrollTo by percentage) have completely different meaning.
The scrollTo by percentage, means that the content will scroll X% of its length. For example, when you scroll-to 50% and your content width is 2000px, it will scroll untill its center (1000px) reaches the left side of the container. If you set it to 10%, it’ll scroll untill 200px etc.
mcs.leftPct returns the general scrolling percentage (0 for start, 100 for end of scrolling). This percentage is set according to the visible area, meaning that when your (2000px) content is scrolled all the way to the right, it’s actually scrolled to 2000px minus its container width which is less than 100% of the 2000px.
Now, to find the scrolled position of your content in percentage (which is what the scrollTo percentage is), you can do:
$(".demo-x").mCustomScrollbar({ axis:"x", advanced:{autoExpandHorizontalScroll:true}, callbacks:{ whileScrolling:function(){ var p=Math.round(Math.abs(this.mcs.content[0].offsetLeft)*100/this.mcs.content.outerWidth()); console.log(p); }, } });
I hope I make sense lol 🙂
Hello Malihu,
thank you for your prompt answer.
Yes now i understand what that mean. But for general use, i think it’s just more useful if scrollTo by percentage goes according by mcs.leftPct.
If i say i want to go to center, i just can write scrollTo(‘50%’) or go to last, scrollTo(‘100%’)
Right now, if write scrollTo(‘78%’) until scrollTo(‘100%’). It will show same result 😀
And sorry to ask again, my question is the reverse one. How to scroll by mcs.leftPct ?
Say goTo(‘50%’) and it scroll until mcs.leftPct = 50% ?
Thanks again
In this case, you can calculate it like this:
/* percentage to scroll-to (e.g. 50%) */ var pct=50; /* the element containing your content */ var cont=$(".content .mCSB_container"); /* calculate where to scroll */ var to=Math.round(Math.abs((cont.outerWidth()-cont.parent().width())*pct/100)); /* do the scrolling */ $(".content").mCustomScrollbar("scrollTo",to);
Change outerWidth()/width() to outerHeight()/height() for vertical scrollbar.
Hi,
I’m trying to implement similar behavior.
The case is that I have expandable elements in the container. Now If I click on a expandable element(and it’s the last visible element) I want to scrolldown the size of the element (after ofcourse the expanding animation has finished, that’s taken care of).
function scrollContainer ( $container, $element ) { $container = $container.find('.mCSB_container'); var containerTop = $container.position().top, containerHeight = $container.parent().height(), containerBottomOffset = containerTop + containerHeight + $element.height(); $container.mCustomScrollbar( 'scrollTo', containerBottomOffset); }
Much appreciation in advance 🙂
@Dkralev
If you need to scroll by a certain amount (e.g. by your
$element.height()
), you can simply do:$container.mCustomScrollbar('scrollTo', '-='+$element.height());
with
'-=pixels'
and'+=pixels'
you can scroll up/down by a pixels amount each time.Hi. I have a problem with the plugin combinate with the select2.js plugin. When I click on the “dragger” and move the mouse, the scroll follows cursor. For example: http://jsfiddle.net/b8LZJ/13/. How can i resolve it? I await your return eagerly. Thanks!
Hello,
Unfortunately this issue can only be solved by editing jquery.mCustomScrollbar.js (version 2.8.1 which is the one you’re using).
What causes this issue
Seems that select2 prevents event bubbling (stops event propagation) on its wrapper element (which contains the options). This prevents the custom scrollbar script to register mouseup events on document that are used to release scrollbar dragging.
Quick (and dirty) solution
Edit jquery.mCustomScrollbar.js (version 2.8.1) and find line: 371.
Replace:
}).bind("mouseup."+$this.data("mCustomScrollbarIndex"),function(e){
with:
}).add(mCSB_dragger).add($this).bind("mouseup."+$this.data("mCustomScrollbarIndex"),function(e){
This should do the trick
Man, I could settle here. Thank you, you helped me a lot.
I have the same problem but I am using version 3.0.4. How can I fix this?
Edit line 1169 and change:
add(mCSB_dragger)
to:
add(mCSB_dragger).add($this)
It worked. Thanks
Hello, I have a problem with mCSB_1_container height. I want it to have 100% of parent div but it has only te content height. Any sugestions? Thanks for help
Hi,
.mCSB_container elements always get
height: auto
(jquery.mCustomScrollbar.css line: 42) because this div defines the actual content height and it’s the div being scrolled.If this div is set to 100%, the scrollbar will never show/work. Scrollbars work on inner divs that overflow their parent.