This website uses cookies to personalise ads and to analyse traffic ok
web design

jQuery custom content scroller

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

When upgrading from version 2.x to 3.x it’s important to use version 3 CSS and .png files. Version 3 is backwards compatible but it’s also a huge overhaul. One significant change is that you don’t need to call the update method manually (the script does it automatically). For more info see changelog.

Version 2 is still maintained and updated here.


How to use it

Get started by downloading the archive which contains the plugin files (and a large amount of HTML demos and examples). Extract and upload jquery.mCustomScrollbar.concat.min.js, jquery.mCustomScrollbar.css and mCSB_buttons.png to your web server (alternatively you can load plugin files from a CDN).

Instead of hosting the plugin files on your web server, you can load them directly from a CDN like jsdelivr, Github etc.

  • jsdelivr versioned/minified
    • //cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/jquery.mCustomScrollbar.concat.min.js
    • //cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/jquery.mCustomScrollbar.min.css
    • //cdn.jsdelivr.net/jquery.mcustomscrollbar/3.0.6/mCSB_buttons.png
  • Github latest/minified
    • //malihu.github.io/custom-scrollbar/jquery.mCustomScrollbar.concat.min.js
    • //malihu.github.io/custom-scrollbar/jquery.mCustomScrollbar.min.css
    • //malihu.github.io/custom-scrollbar/mCSB_buttons.png


HTML

Include jquery.mCustomScrollbar.css in the head tag your HTML document (more info)

jquery.mCustomScrollbar.css contains the styling of the custom scrollbar and themes. It should normally be included in the head tag of your html (typically before any script tags). If you wish to reduce http requests and/or have all your website stylesheet in a single file, you should move/copy scrollbars styling in your main CSS document.

mCSB_buttons.png contains all the button arrows (up, down, left and right) as image sprites for all scrollbar themes. The plugin archive contains the PSD source (source-files/mCSB_buttons.psd) so you can change them or add your own. This file should be in the same directory with plugin stylesheet.


<link rel="stylesheet" href="/path/to/jquery.mCustomScrollbar.css" />

Include jQuery library (if your project doesn’t use it already) and jquery.mCustomScrollbar.concat.min.js in the head tag or at the very bottom of your document, just before the closing body tag

Some frameworks and CMS include jQuery library in the head tag to make sure it’s loaded when other scripts request it. Usually, including .js files on the bottom of the HTML document (just before the closing body tag) is recommended for better performance. In any case, jQuery must be included first, before plugin scripts.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/path/to/jquery.mCustomScrollbar.concat.min.js"></script>

CSS

The element(s) you want to add scrollbar(s) should have the typical CSS properties of an overflowed block which are a height (or max-height) value, an overflow value of auto (or hidden) and content long enough to require scrolling. For horizontal scrollbar, the element should have a width (or max-width) value set.

If you prefer to set your element’s height/width via javascript, you can use the setHeight/setWidth option parameters.

Initialization

Initialize via javascript

After files inclusion, call mCustomScrollbar function on the element selector you want to add the scrollbar(s)

<script>
    (function($){
        $(window).on("load",function(){
            $(".content").mCustomScrollbar();
        });
    })(jQuery);
</script>

more info

The code is wrapped in (function($){ ... })(jQuery);. This ensures no conflict between jQuery and other libraries using $ shortcut (see Avoiding Conflicts with Other Libraries for more info). The plugin function is called in $(window).on("load") so it executes after all page elements (like images) are loaded.

You can change the function selector ".content" to any selector you want (an element id, class name, js variable etc.). For instance, if you want custom scrollbars to apply on the element with id content-1, you simply do:

$("#content-1").mCustomScrollbar();

You may also have multiple selectors by inserting comma separated values

$(".content,#content-1").mCustomScrollbar();

The above code adds custom scrollbars to a)every element with class name content and b)the element with id content-1.

Additionally, you may want to call mCustomScrollbar multiple times within a page in order to set different options (configuration and option parameters explained below) for each selector

<script>
  (function($){
    $(window).on("load",function(){
      $("#vertical-content").mCustomScrollbar({
        theme:"light-3",
        scrollButtons:{
          enable:true
        }
      });
      $("#horizontal-content").mCustomScrollbar({
        axis:"x",
        theme:"3d"
      });
    });
  })(jQuery);
</script>

Initialize via HTML

Add the class mCustomScrollbar to any element you want to add custom scrollbar(s) with default options. Optionally, set its axis via the HTML data attribute data-mcs-axis (e.g. "x" for horizontal and "y" for vertical) and its theme via data-mcs-theme. For example:

<div class="mCustomScrollbar" data-mcs-theme="dark">
  <!-- your content -->
</div>

Basic configuration & option parameters

axis

By default, the script applies a vertical scrollbar. To add a horizontal or 2-axis scrollbars, invoke mCustomScrollbar function with the axis option set to "x" or "yx" respectively

$(".content").mCustomScrollbar({
    axis:"x" // horizontal scrollbar
});
$(".content").mCustomScrollbar({
    axis:"yx" // vertical and horizontal scrollbar
});

theme

To quickly change the appearance of the scrollbar, set the theme option parameter to any of the ready-to-use themes available in jquery.mCustomScrollbar.css, for example:

$(".content").mCustomScrollbar({
    theme:"dark"
});

Configuration

You can configure your scrollbar(s) using the following option parameters on mCustomScrollbar function
Usage $(selector).mCustomScrollbar({ option: value });

setWidth: false
Set the width of your content (overwrites CSS width), value in pixels (integer) or percentage (string).
setHeight: false
Set the height of your content (overwrites CSS height), value in pixels (integer) or percentage (string).
setTop: 0
Set the initial css top property of content, accepts string values (css top position).
Example: setTop: "-100px".
setLeft: 0
Set the initial css left property of content, accepts string values (css left position).
Example: setLeft: "-100px".
axis: "string"
Define content’s scrolling axis (the type of scrollbars added to the element: vertical and/of horizontal).
Available values: "y", "x", "yx".

  • axis: "y" – vertical scrollbar (default)
  • axis: "x" – horizontal scrollbar
  • axis: "yx" – vertical and horizontal scrollbars
scrollbarPosition: "string"
Set the position of scrollbar in relation to content.
Available values: "inside", "outside".
Setting scrollbarPosition: "inside" (default) makes scrollbar appear inside the element. Setting scrollbarPosition: "outside" makes scrollbar appear outside the element. Note that setting the value to "outside" requires your element (or parent elements) to have CSS position: relative (otherwise the scrollbar will be positioned in relation to document’s root element).
scrollInertia: integer
Set the amount of scrolling momentum as animation duration in milliseconds.
Higher value equals greater scrolling momentum which translates to smoother/more progressive animation. Set to 0 to disable.
autoDraggerLength: boolean
Enable or disable auto-adjusting scrollbar dragger length in relation to scrolling amount (same bahavior with browser’s native scrollbar).
Set autoDraggerLength: false when you want your scrollbar to (always) have a fixed size.
autoHideScrollbar: boolean
Enable or disable auto-hiding the scrollbar when inactive.
Setting autoHideScrollbar: true will hide the scrollbar(s) when scrolling is idle and/or cursor is out of the scrolling area.
Please note that some special themes like “minimal” overwrite this option.
autoExpandScrollbar: boolean
Enable or disable auto-expanding the scrollbar when cursor is over or dragging the scrollbar.
alwaysShowScrollbar: integer
Always keep scrollbar(s) visible, even when there’s nothing to scroll.

  • alwaysShowScrollbar: 0 – disable (default)
  • alwaysShowScrollbar: 1 – keep dragger rail visible
  • alwaysShowScrollbar: 2 – keep all scrollbar components (dragger, rail, buttons etc.) visible
snapAmount: integer
Make scrolling snap to a multiple of a fixed number of pixels. Useful in cases like scrolling tabular data, image thumbnails or slides and you need to prevent scrolling from stopping half-way your elements. Note that your elements must be of equal width or height in order for this to work properly.
To set different values for vertical and horizontal scrolling, use an array: [y,x]
snapOffset: integer
Set an offset (in pixels) for the snapAmount option. Useful when for example you need to offset the snap amount of table rows by the table header.
mouseWheel:{ enable: boolean }
Enable or disable content scrolling via mouse-wheel.
mouseWheel:{ scrollAmount: integer }
Set the mouse-wheel scrolling amount (in pixels). The default value "auto" adjusts scrolling amount according to scrollable content length.
mouseWheel:{ axis: "string" }
Define the mouse-wheel scrolling axis when both vertical and horizontal scrollbars are present.
Set axis: "y" (default) for vertical or axis: "x" for horizontal scrolling.
mouseWheel:{ preventDefault: boolean }
Prevent the default behaviour which automatically scrolls the parent element when end or beginning of scrolling is reached (same bahavior with browser’s native scrollbar).
mouseWheel:{ deltaFactor: integer }
Set the number of pixels one wheel notch scrolls. The default value “auto” uses the OS/browser value.
mouseWheel:{ normalizeDelta: boolean }
Enable or disable mouse-wheel (delta) acceleration. Setting normalizeDelta: true translates mouse-wheel delta value to -1 or 1.
mouseWheel:{ invert: boolean }
Invert mouse-wheel scrolling direction. Set to true to scroll down or right when mouse-wheel is turned upwards.
mouseWheel:{ disableOver: [array] }
Set the tags that disable mouse-wheel when cursor is over them.
Default value:
["select","option","keygen","datalist","textarea"]
scrollButtons:{ enable: boolean }
Enable or disable scrollbar buttons.
scrollButtons:{ scrollAmount: integer }
Set the buttons scrolling amount (in pixels). The default value "auto" adjusts scrolling amount according to scrollable content length.
scrollButtons:{ scrollType: "string" }
Define the buttons scrolling type/behavior.

  • scrollType: "stepless" – continuously scroll content while pressing the button (default)
  • scrollType: "stepped" – each button click scrolls content by a certain amount (defined in scrollAmount option above)
scrollButtons:{ tabindex: integer }
Set a tabindex value for the buttons.
keyboard:{ enable: boolean }
Enable or disable content scrolling via the keyboard.
The plugin supports the directional arrows (top, left, right and down), page-up (PgUp), page-down (PgDn), Home and End keys.
keyboard:{ scrollAmount: integer }
Set the keyboard arrows scrolling amount (in pixels). The default value "auto" adjusts scrolling amount according to scrollable content length.
keyboard:{ scrollType: "string" }
Define the keyboard arrows scrolling type/behavior.

  • scrollType: "stepless" – continuously scroll content while pressing the arrow key (default)
  • scrollType: "stepped" – each key release scrolls content by a certain amount (defined in scrollAmount option above)
contentTouchScroll: integer
Enable or disable content touch-swipe scrolling for touch-enabled devices.
To completely disable, set contentTouchScroll: false.
Integer values define the axis-specific minimum amount required for scrolling momentum (default: 25).
documentTouchScroll: boolean
Enable or disable document touch-swipe scrolling for touch-enabled devices.
advanced:{ autoExpandHorizontalScroll: boolean }
Auto-expand content horizontally (for "x" or "yx" axis).
If set to true, content will expand horizontally to accommodate any floated/inline-block elements.
Setting its value to 2 (integer) forces the non scrollHeight/scrollWidth method. A value of 3 forces the scrollHeight/scrollWidth method.
advanced:{ autoScrollOnFocus: "string" }
Set the list of elements/selectors that will auto-scroll content to their position when focused.
For example, when pressing TAB key to focus input fields, if the field is out of the viewable area the content will scroll to its top/left position (same bahavior with browser’s native scrollbar).
To completely disable this functionality, set autoScrollOnFocus: false.
Default:
"input,textarea,select,button,datalist,keygen,a[tabindex],area,object,[contenteditable='true']"
advanced:{ updateOnContentResize: boolean }
Update scrollbar(s) automatically on content, element or viewport resize.
The value should be true (default) for fluid layouts/elements, adding/removing content dynamically, hiding/showing elements etc.
advanced:{ updateOnImageLoad: boolean }
Update scrollbar(s) automatically each time an image inside the element is fully loaded.
Default value is auto which triggers the function only on "x" and "yx" axis (if needed).
The value should be true when your content contains images and you need the function to trigger on any axis.
advanced:{ updateOnSelectorChange: "string" }
Update scrollbar(s) automatically when the amount and size of specific selectors changes.
Useful when you need to update the scrollbar(s) automatically, each time a type of element is added, removed or changes its size.
For example, setting updateOnSelectorChange: "ul li" will update scrollbars each time list-items inside the element are changed.
Setting the value to true, will update scrollbars each time any element is changed.
To disable (default) set to false.
advanced:{ extraDraggableSelectors: "string" }
Add extra selector(s) that’ll release scrollbar dragging upon mouseup, pointerup, touchend etc.
Example: extraDraggableSelectors: ".myClass, #myID"
advanced:{ releaseDraggableSelectors: "string" }
Add extra selector(s) that’ll allow scrollbar dragging upon mousemove/up, pointermove/up, touchend etc.
Example: releaseDraggableSelectors: ".myClass, #myID"
advanced:{ autoUpdateTimeout: integer }
Set the auto-update timeout in milliseconds.
Default timeout: 60
theme: "string"
Set the scrollbar theme.
View all ready-to-use themes
All themes are contained in plugin’s CSS file (jquery.mCustomScrollbar.css).
Default theme: "light"
callbacks:{
      onCreate: function(){}
}
A function to call when plugin markup is created.
Example:
callbacks:{
    onCreate:function(){
      console.log("Plugin markup generated");
    }
}
callbacks:{
      onInit: function(){}
}
A function to call when scrollbars have initialized (demo).
Example:
callbacks:{
    onInit:function(){
      console.log("Scrollbars initialized");
    }
}
callbacks:{
      onScrollStart: function(){}
}
A function to call when scrolling starts (demo).
Example:
callbacks:{
    onScrollStart:function(){
      console.log("Scrolling started...");
    }
}
callbacks:{
      onScroll: function(){}
}
A function to call when scrolling is completed (demo).
Example:
callbacks:{
    onScroll:function(){
      console.log("Content scrolled...");
    }
}
callbacks:{
      whileScrolling: function(){}
}
A function to call while scrolling is active (demo).
Example:
callbacks:{
    whileScrolling:function(){
      console.log("Scrolling...");
    }
}
callbacks:{
      onTotalScroll: function(){}
}
A function to call when scrolling is completed and content is scrolled all the way to the end (bottom/right) (demo).
Example:
callbacks:{
    onTotalScroll:function(){
      console.log("Scrolled to end of content.");
    }
}
callbacks:{
      onTotalScrollBack: function(){}
}
A function to call when scrolling is completed and content is scrolled back to the beginning (top/left) (demo).
Example:
callbacks:{
    onTotalScrollBack:function(){
      console.log("Scrolled back to the beginning of content.");
    }
}
callbacks:{
      onTotalScrollOffset: integer
}
Set an offset for the onTotalScroll option.
For example, setting onTotalScrollOffset: 100 will trigger the onTotalScroll callback 100 pixels before the end of scrolling is reached.
callbacks:{
      onTotalScrollBackOffset: integer
}
Set an offset for the onTotalScrollBack option.
For example, setting onTotalScrollBackOffset: 100 will trigger the onTotalScrollBack callback 100 pixels before the beginning of scrolling is reached.
callbacks:{
      alwaysTriggerOffsets: boolean
}
Set the behavior of calling onTotalScroll and onTotalScrollBack offsets.
By default, callback offsets will trigger repeatedly while content is scrolling within the offsets.
Set alwaysTriggerOffsets: false when you need to trigger onTotalScroll and onTotalScrollBack callbacks once, each time scroll end or beginning is reached.
callbacks:{
      onOverflowY: function(){}
}
A function to call when content becomes long enough and vertical scrollbar is added.
Example:
callbacks:{
    onOverflowY:function(){
      console.log("Vertical scrolling required");
    }
}
callbacks:{
      onOverflowX: function(){}
}
A function to call when content becomes wide enough and horizontal scrollbar is added.
Example:
callbacks:{
    onOverflowX:function(){
      console.log("Horizontal scrolling required");
    }
}
callbacks:{
      onOverflowYNone: function(){}
}
A function to call when content becomes short enough and vertical scrollbar is removed.
Example:
callbacks:{
    onOverflowYNone:function(){
      console.log("Vertical scrolling is not required");
    }
}
callbacks:{
      onOverflowXNone: function(){}
}
A function to call when content becomes narrow enough and horizontal scrollbar is removed.
Example:
callbacks:{
    onOverflowXNone:function(){
      console.log("Horizontal scrolling is not required");
    }
}
callbacks:{
      onBeforeUpdate: function(){}
}
A function to call right before scrollbar(s) are updated.
Example:
callbacks:{
    onBeforeUpdate:function(){
      console.log("Scrollbars will update");
    }
}
callbacks:{
      onUpdate: function(){}
}
A function to call when scrollbar(s) are updated.
Example:
callbacks:{
    onUpdate:function(){
      console.log("Scrollbars updated");
    }
}
callbacks:{
      onImageLoad: function(){}
}
A function to call each time an image inside the element is fully loaded and scrollbar(s) are updated.
Example:
callbacks:{
    onImageLoad:function(){
      console.log("Image loaded");
    }
}
callbacks:{
      onSelectorChange: function(){}
}
A function to call each time a type of element is added, removed or changes its size and scrollbar(s) are updated.
Example:
callbacks:{
    onSelectorChange:function(){
      console.log("Scrollbars updated");
    }
}
live: "string"
Enable or disable applying scrollbar(s) on all elements matching the current selector, now and in the future.
Set live: true when you need to add scrollbar(s) on elements that do not yet exist in the page. These could be elements added by other scripts or plugins after some action by the user takes place (e.g. lightbox markup may not exist untill the user clicks a link).
If you need at any time to disable or enable the live option, set live: "off" and "on" respectively.
You can also tell the script to disable live option after the first invocation by setting live: "once".
liveSelector: "string"
Set the matching set of elements (instead of the current selector) to add scrollbar(s), now and in the future.

Plugin methods

Ways to execute various plugin actions programmatically from within your script(s).

update

Usage $(selector).mCustomScrollbar("update");

Call the update method to manually update existing scrollbars to accommodate new content or resized element(s). This method is by default called automatically by the script (via updateOnContentResize option) when the element itself, its content or scrollbar size changes.

view examples

/* initialize plugin with auto-update options disabled */
$(selector).mCustomScrollbar({
  advanced:{
    updateOnContentResize: false,
    updateOnImageLoad: false
  }
});

/* at some point in your js script/code update scrollbar manually */
$(selector).mCustomScrollbar("update");

scrollTo

Usage $(selector).mCustomScrollbar("scrollTo",position,options);

Call the scrollTo method to programmatically scroll the content to the position parameter (demo).

position parameter

Position parameter can be:

  • "string"
    • e.g. element selector: "#element-id"
    • e.g. special pre-defined position: "bottom"
    • e.g. number of pixels less/more: "-=100"/"+=100"
  • integer
    • e.g. number of pixels: 100
  • [array]
    • e.g. different y/x position: [100,50]
  • object/function
    • e.g. jQuery object: $("#element-id")
    • e.g. js object: document.getelementbyid("element-id")
    • e.g. function: function(){ return 100; }

Pre-defined position strings:

  • "bottom" – scroll to bottom
  • "top" – scroll to top
  • "right" – scroll to right
  • "left" – scroll to left
  • "first" – scroll to the position of the first element within content
  • "last" – scroll to the position of the last element within content

view examples

Scroll to element with id “#el-1″

$(selector).mCustomScrollbar("scrollTo","#el-1");

Scroll to top

$(selector).mCustomScrollbar("scrollTo","top");

Scroll by 100 pixels down or right

var val=100;
$(selector).mCustomScrollbar("scrollTo","-="+val);

Scroll by 100 pixels up or left

$(selector).mCustomScrollbar("scrollTo","+=100");

Scroll by 100 pixels down and by 50 pixels right

$(selector).mCustomScrollbar("scrollTo",["-=100","-=50"]);

Scroll to the fifth paragraph

$(selector).mCustomScrollbar("scrollTo",$("p:eq(4)"));

Scroll to the last element within your content

$(selector).mCustomScrollbar("scrollTo","last");

Scroll to some variable value

var val=document.getelementbyid("element-id");
$(selector).mCustomScrollbar("scrollTo",val);

Scroll to 300 pixels

$(selector).mCustomScrollbar("scrollTo",300);

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);

view examples

/* initialize plugin */
$(selector).mCustomScrollbar();

/* at some point in your js script/code disable scrollbar */
$(selector).mCustomScrollbar("disable");

/* re-enable scrollbar as needed */
$(selector).mCustomScrollbar("update");

destroy

Usage $(selector).mCustomScrollbar("destroy");

Calling destroy method will completely remove the custom scrollbar and return the element to its original state (demo).

view examples

/* initialize plugin */
$(selector).mCustomScrollbar();

/* at some point in your js script/code destroy scrollbar */
$(selector).mCustomScrollbar("destroy");

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"
});

View all ready-to-use themes

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; }

Custom scrollbar layout

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 starts
  • whileScrolling – triggers while scroll event is running
  • onScroll – triggers when a scroll event completes
  • onTotalScroll – triggers when content has scrolled all the way to bottom or right
  • onTotalScrollBack – 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).

The following will trigger the callback function when content has scrolled to bottom minus 100 pixels

$(".content").mCustomScrollbar({
    callbacks:{
        onTotalScroll:function(){
            console.log("scrolled to bottom");
        },
    onTotalScrollOffset:100
    }
});

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).

$(".content").mCustomScrollbar({
    callbacks:{
        onTotalScroll:function(){
            console.log("scrolled to bottom");
        },
    onTotalScrollOffset:100,
    alwaysTriggerOffsets:false
    }
});

Additional callbacks:

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 object
  • this.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 percentage
  • this.mcs.leftPct – content horizontal scrolling percentage
  • this.mcs.direction – content’s scrolling direction (y or x)

view examples

Load more content when scrolled to bottom

$(selector).mCustomScrollbar({
    callbacks:{
        onTotalScroll:function(){
            this.mcs.content.append("...");
        }
    }
});

Run code when at least half of the content is scrolled

$(selector).mCustomScrollbar({
    callbacks:{
        whileScrolling:function(){
            var pct=this.mcs.topPct;
            if(pct>=50){
              /* do something... */
            }
        }
    }
});

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

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

Pages: 1 2 3 4


5,627 Comments

Post a comment

Comments pages: 1 20 21 22 23 24 85

  1. Sanil Shinde
    Posted on October 22, 2012 at 15:52 Permalink

    Hi,

    It is possible to set horizontal and vertical scroll at same time. Would you please provide a sample for horizontal and vertical scroll bar at same time.

    Thanks & Regards,
    Sanil Shinde.

    Reply
  2. John
    Posted on October 22, 2012 at 01:23 Permalink

    I really love this scroll bar. there is so many of them on the web that are really bad lol. I’m going to come back later in a few months and make a donation.

    Is there no way to control the speed of scroll to?

    Reply
    • malihu
      Posted on October 22, 2012 at 18:05 Permalink

      Not really. It scrolls to position instantly.

      Reply
  3. Praveen Kumar
    Posted on October 21, 2012 at 23:30 Permalink

    Hi malihu, amazing blog this is! πŸ˜€

    I tried the plugin, it appears but doesn’t scroll down. The console shows this error,

    ‘Uncaught TypeError: Object [object Object] has no method ‘draggable’ ‘
    refering to the line no. 296 in the jquery.mCustomScrollbar.js

    can you please clarify this?
    also, the scroll bar doesn’t disappear when the content is not long enough.

    i haven’t changed a thing in the code i forked from git.

    Reply
    • John
      Posted on October 22, 2012 at 00:00 Permalink

      i just started using this plug in too. I had some issues. make sure you are using jquery 1.8 and jquery UI 1.8.24

      Reply
    • Praveen Kumar
      Posted on October 22, 2012 at 00:04 Permalink

      Hello again,

      I include in the html document, the jquery-ui-1.8.21.custom.min.js file, and now the scroll is working. But the length of the scroll is fixed.

      http://www.saarang.org/2013/site/main2/#hospitality_page

      Please check this link for seeing what i’m referring to.
      The site is under development still, so please excuse any malfunctions. Please do suggest any improvements that you feel, we’ll all be very happy to incorporate them.

      Cheers!

      Reply
  4. derek
    Posted on October 21, 2012 at 03:46 Permalink

    nice plugin

    Reply
  5. perLover
    Posted on October 21, 2012 at 03:29 Permalink

    Hi. Another doubt: It’s possible to have the dragger rail (and obviously all the scroll functionality) restricted to a size smaller than the content? I mean, using horizontal version, imagine a gallery filling the full screen width, but scrollbar (rail+dragger) only filling a fixed size, like 400px.

    Thanks in advance.

    Reply
    • malihu
      Posted on October 21, 2012 at 08:18 Permalink

      Yes of course. For horizontal scrollbar, set .mCSB_scrollTools css width to what you need. For example, adding the following rules will make your horizontal scrollbar 400 pixels wide and horizontally centered:
      .mCSB_horizontal.mCustomScrollBox .mCSB_scrollTools{ width:400px; left:50%; margin-left:-200px; }

      Reply
  6. Juan Rangel
    Posted on October 20, 2012 at 21:04 Permalink

    Hello malihu:
    It’ a great plugin, I have a problem but i don’t know if the thing that i try to made it’s possible, i try to put the two scrollbars on the same div, horizontal and vertical, is it possible??
    If is possible can you help me?, thanks

    Reply
    • perLover
      Posted on October 21, 2012 at 03:27 Permalink

      Hi Juan. Check question 41. πŸ˜‰

      Reply
      • Juan Rangel
        Posted on October 21, 2012 at 03:54 Permalink

        Thanks perLover, i’m going to try another option, if i solve my problem, i’ll post how i have solved it, sorry for my written, i don’t have a good english

        Reply
  7. perLover
    Posted on October 20, 2012 at 18:27 Permalink

    Hi. Wonderfull plugin.
    One small doubt. I’m trying to place the whole scrollbar on top (using horizontal configuration).
    I’m placing the .mCSB_scrollTools with css() on top:0px (i can’t use negative values, as it’s insde the wrapper). After that i’ve move the images_container to top:20px.

    My problem is that event when i setup a set_height config parameter 20px more than images, they look cutted on bottom (those 20px).

    Can you point me in the right direction?
    Thanks a bunch.

    Reply
    • perLover
      Posted on October 20, 2012 at 19:07 Permalink

      Ok, don’t worry, i solved, styling the .mCSB_container object directly.
      Thanks again for such a fantastic plugin. I’ll make a donation once the project finished and charged.

      Reply
  8. Nicolas Cadilhac
    Posted on October 19, 2012 at 21:51 Permalink

    Seems like there is a problem in this situation: I have 2 tabs. When the user clicks one tab, the only container that uses your script receives content related to this tab. When the other tab is clicked, content is cleared and replaced with another set of content. Of course Update is called each time to refresh the scrollbar.

    Because the scrollbar may not be at the top position when I click on the second tab, I also call ScrollTo “top” after setting the new content. The problem appears when the new content is small and there is no need of a scrollbar. Update correctly removes the scrollbar but then calling ScrollTo “top” makes the content disappear (I checked with firebug and in fact it has been scrolled out of and above the window).

    Any idea?

    Reply
    • malihu
      Posted on October 20, 2012 at 05:37 Permalink

      Without knowing exactly what your code is like, you could add a simple condition for calling scrollTo (e.g. scroll to top only if scrollbar does exist):
      if(!$(".content .mCSB_container").is(".mCS_no_scrollbar")){ $(".content").mCustomScrollbar("scrollTo","top"); }

      Reply
      • Nicolas Cadilhac
        Posted on October 20, 2012 at 16:40 Permalink

        Thanks. This is actually what I did already since I noticed that when setting new content and calling update, the scrollbar aws not there anymore and the content was correctly scrolled on top.

        I can’t show you my long code, but in pseudo code it is:
        – $(“.content .mCSB_container”).empty()
        – append some new content inside $(“.content .mCSB_container”)
        – call Update
        – call ScrollTo

        There may be a bug in your ScroollTo code when there is no scrollbar?

        Reply
        • malihu
          Posted on October 21, 2012 at 08:26 Permalink

          If you completely replace the content (e.g. via .empty() and .append()) you don’t really need calling the scrollTo method after. Try inserting scrollTo at the top before emptying your content. If you could sent me your file(s) via e-mail I believe I could help much better.

          Reply
  9. Erin
    Posted on October 19, 2012 at 19:39 Permalink

    Hello!

    Awesome plugin, by the way, and it works great everywhere in my page EXCEPT….

    …when I try to use it in conjunction with ColorBox (a modal box/lightbox plugin).

    What happens is, if I click on the link that makes the ColorBox pop up right before everything loads on page, it appears that the scrollbar script STARTS working, but either doesn’t form the scrollbar (but starts to form the content box), or it loads properly, but won’t work again if I wait for everything on the page to load before clicking on the link to make ColorBox pop up.

    I am not really stealth with jQuery/script, so debugging is a bit of a nightmare for me. I have to use all these different plugins to give the client their desired results, but I’m afraid there are conflicts I’m not sure how to fix. But when I temporarily turn off the other plugins, the scrollbar still doesn’t work properly in ColorBox.

    Halp? πŸ™‚

    http://www.brittondev.com/colwell/index2.html
    Click on ‘Contact Us’ in the footer menu, bottom right. This is what I’m using to develop for my other pop up boxes.

    Thank you so much!
    Erin

    Reply
    • malihu
      Posted on October 20, 2012 at 06:09 Permalink

      Hi,
      It seems that you apply the custom scrollbar on the .scrollit_footer element which ColorBox script adds and removes dynamically. This element is added only when you click your footer link and it’s completely removed when clicking the close icon.

      You can try calling $(".scrollit_footer").mCustomScrollbar() inside the onOpen callback of colorbox function (instead of window load).

      Another way would be to apply the scrollbar on .cboxContent (or some other element that does always exist in your markup) and probably call the update method in the onOpen callback.

      Reply
  10. Mufeed Ahmad
    Posted on October 19, 2012 at 08:31 Permalink

    Hi,

    It’s awesome.

    I have some issues:

    1. Whenever i try it with my slideUp(); and slideDown(); content it doesn’t create any scrollbar

    2. scrollTo.. anchor tag smooth scrolling doesn’t work with it.

    Please help!

    Many thanks,
    Mufeed Ahmad

    Reply
    • malihu
      Posted on October 19, 2012 at 18:30 Permalink

      Hi,
      You need to call plugin’s update method as a callback to your slideDown function (see “Hiding & showing content blocks with custom scrollbars” for more info). For example:
      $(".content").slideDown("slow",function(){ $(this).mCustomScrollbar("update"); });

      Reply
  11. deca
    Posted on October 18, 2012 at 19:47 Permalink

    Everything in this plugin is working except Easing. I am using the lastest download with jQuery 1.8.2 and your custom jquery-ui-1.8.23.custom.min.js file.

    scrollTo has no easing, as well as mousewheel or continuous scrolling.

    Reply
    • deca
      Posted on October 18, 2012 at 22:18 Permalink

      Seems to be related to this in the scroll function:

      if($.browser.webkit){ /*fix webkit zoom and jquery animate*/
      var screenCssPixelRatio=(window.outerWidth-8)/window.innerWidth,
      isZoomed=(screenCssPixelRatio1.02);
      }

      then the next line checks for it
      if($this.data(“scrollInertia”)===0 || isZoomed)

      and no animate method is called. Why would you have this check for Chrome ? Removing it makes it work. Any reason this would be?

      Reply
      • malihu
        Posted on October 19, 2012 at 03:03 Permalink

        Because when Chrome browser is zoomed (in or out) the scrolling animation bugs. Is your Chrome zoomed? Viewing the page without any zoom (100%) on Chrome will gain back easing.

        Reply
  12. Jessica
    Posted on October 18, 2012 at 18:50 Permalink

    I have the styles showing in the html, but this style “mCSB_scrollTools” is always displaying as display:none; And my regular scroll bar is always showing on the content container. Any idea why??

    Reply
    • Jessica
      Posted on October 18, 2012 at 21:25 Permalink

      I found the issue. I was using max-height instead of height. Per your solution above, I used the code below to hook up my content to my scroll bar, and all is well now! Thanks!

      (function($){
      $(window).load(function(){
      var maxHeightDiv=$(“#comment-items”),
      maxHeight=parseInt(maxHeightDiv.css(“max-height”));
      maxHeightDiv.mCustomScrollbar();
      if(maxHeightDiv.find(“.mCSB_container”).outerHeight()>maxHeight){
      maxHeightDiv.css({“height”:maxHeight}).mCustomScrollbar(“update”);
      }else{
      maxHeightDiv.css({“height”:”auto”}).mCustomScrollbar(“update”);
      }
      });
      })(jQuery);

      Reply
  13. Cedric
    Posted on October 18, 2012 at 11:39 Permalink

    Hi

    I’m trying to include this scrollbar in a website, and it’s almost working, just one thing is broken:
    If I drag the scrollbar with my mouse, it remains “sticked” to my cursor, i.e. the mouseUp event seems to be somehow ignored. Clicking out of the area doesn’t help…
    Do you have any idea what could cause this, because i couldn’t figure it out.

    Cheers

    Reply
  14. jack
    Posted on October 18, 2012 at 01:51 Permalink

    Cancel the last, I just saw what I needed in another post and copied it. Now the buttons appear. All I’d like to do now is change the length of the dragger bar and enable it to go right to the top and bottom of the dragger rail. I’m so close I can feel it. Any help would be much appreciated and if I can implement it on my site then it will be well worth a donation.

    Reply
    • malihu
      Posted on October 18, 2012 at 06:00 Permalink

      The scrollbar expands to full height by default and the dragger bar can be scrolled from top to bottom. All the styling is done via the CSS. I can’t really tell what you need so if you can send me a screen-shot or a link I might be able to help.

      Reply
      • Jack
        Posted on October 18, 2012 at 14:50 Permalink

        Hello, Thank you so much for responding to someone like me that has so little knowledge. I’d like just the dragger bar to be a little shorter and not take up so much room in the dragger rail. I tried setting the height to less and making a single CSS rule for the dragger bar but it didn’t work. I’d like to send a screenshot but I don’t know where to send it? This is a minor detail but I’d really like to get it to resemble my PSD composite as closely as possible. I would really appreciate any help. Many thanks.

        Jack

        Reply
        • malihu
          Posted on October 19, 2012 at 03:17 Permalink

          By default, the dragger bar auto-adjusts its length according to scrollable content (the more the scrolling, the longer the dragger bar). If you see a long dragger bar, it means your content needs little scrolling (just like browser’s native scrollbar work).

          If you want to have a non-adjustable fixed size dragger bar, set autoDraggerLength option parameter to false:
          $(".content").mCustomScrollbar({ autoDraggerLength: false });

          and set its (.mCSB_dragger) height normally via CSS.

          Reply
  15. jack
    Posted on October 18, 2012 at 01:14 Permalink

    Hello, your plugin and tutorial is exactly what I’m looking for to make my portfolio site work. However, I’m not a coder and I can’t see how to make the scroll buttons activate? I need the buttons to appear top and bottom. Could you tell me how to show them please.

    Many thanks

    Jack

    Reply
  16. paul
    Posted on October 17, 2012 at 22:47 Permalink

    With jquery > 1.8, I had problem making mCustomScrollbar work, then digging deeper, I changed all outerWidth() and outerHeight() to outerWidth(true) and outerHeight(true), since these methods have been updated. Now it works !!!

    Reply
    • John
      Posted on October 22, 2012 at 15:55 Permalink

      Hey paul i dont see any outerwidth or outerheight in the mcustomscrollbar script ?????

      Reply
      • John
        Posted on October 22, 2012 at 16:08 Permalink

        lol nevermind wasnt looking at the right script had another script named scrollbar that was still opened :p

        Reply
  17. Dan
    Posted on October 17, 2012 at 22:26 Permalink

    Seems my scrollbar stops working in jQuery 1.8.x, fine in 1.7. Anyone encounter this? The DOM elements are correctly placed in the container but they are set to display:none and if I pull that style out of there with Firebug I can’t actually scroll with the bar that appears.
    No JS errors though.

    Any ideas?

    Reply
    • malihu
      Posted on October 18, 2012 at 00:52 Permalink

      Use jQuery 1.8.x with latest jQuery UI version (1.8.23+). I have a custom 1.8.23 build in the download archive.

      Reply
    • Dan
      Posted on October 18, 2012 at 01:07 Permalink

      Doh! It was just because my testing document had slipped in to quirks mode, and my $(window).height() was all messed up, making the scrollcontainer huge.

      In a roundabout way though Paul you did help me realise that, so thanks for posting!

      Reply
  18. Aztul
    Posted on October 17, 2012 at 16:56 Permalink

    Hey.

    I have a problem using this plugin and the jquery-ui autocomplete.

    When I right click or left click on a autocomplete result, the content is automatically scrolling to top. Have you ever hear about this issue ? Do you know what can it be ?

    I have made a stackoverflow to explain my problem :

    Problem explained

    Reply
    • Aztul
      Posted on October 17, 2012 at 18:12 Permalink

      I think I found the problem. You’re making some kind of check here on line 526 :

      if (mCSB_containerY + focusedElemY >= 0 && mCSB_containerY + focusedElemY <= mCustomScrollBoxH - focusedElemH)

      But focusedElemY = focusedElem.position().top and the position top returned is given relative to the first position ancestor, which is in the autocomplete the absolute positioned box.

      Thus wherever the focusedElemY will be on the content page, it will always return the same coordinates.

      Dunno if i’m clear.

      I think the solution would be to extend the position() method and give it the ancestor as argument.

      I found this code :

      /** * Get the current coordinates of the first element in the set of matched * elements, relative to the closest positioned ancestor element that * matches the selector. * @param {Object} selector */ jQuery.fn.positionAncestor = function(selector) { var left = 0; var top = 0; this.each(function(index, element) { // check if current element has an ancestor matching a selector // and that ancestor is positioned var $ancestor = $(this).closest(selector); if ($ancestor.length && $ancestor.css("position") !== "static") { var $child = $(this); var childMarginEdgeLeft = $child.offset().left - parseInt($child.css("marginLeft"), 10); var childMarginEdgeTop = $child.offset().top - parseInt($child.css("marginTop"), 10); var ancestorPaddingEdgeLeft = $ancestor.offset().left + parseInt($ancestor.css("borderLeftWidth"), 10); var ancestorPaddingEdgeTop = $ancestor.offset().top + parseInt($ancestor.css("borderTopWidth"), 10); left = childMarginEdgeLeft - ancestorPaddingEdgeLeft; top = childMarginEdgeTop - ancestorPaddingEdgeTop; // we have found the ancestor and computed the position // stop iterating return false; } }); return { left: left, top: top } };

      Not tested yet but i think the idea is the same.

      Reply
      • malihu
        Posted on October 17, 2012 at 19:18 Permalink

        Thanks a lot for posting this, I’ll check it asap. Thanks for the feedback.

        Reply
  19. Roshan Chaudhary
    Posted on October 17, 2012 at 14:34 Permalink

    Thanks for a great article and plugin.

    Reply
  20. Ani
    Posted on October 16, 2012 at 23:51 Permalink

    This is great, the only drawback is that it defaults to the OS scrollbar for touch devices, it should still be skinned (that’s the whole purpose of using this) and using touch events to scroll (there is the touchwipe jquery plugin to help with that).

    Currently on iOS I also have to double click on the divs in order to be able to scroll and sometimes it doesn’t even work, is this a glitch caused by the plugin?

    Reply
    • malihu
      Posted on October 17, 2012 at 01:44 Permalink

      The plugin applies simple CSS overflow rules to iOS so I don’t think it’s the cause for such issues. I have an iPad 2 running iOS 6.0 and it works very smoothly so maybe it depends on the scrollable content or the device itself.

      When I have enough time I’ll probably try implementing custom scrollbars for touch devices. I need time cause it’ll require additional coding and many hours for testing (consider Android, iOS, Windows phone, few OS versions for each one and at least half a dozen mobile browsers…)

      Reply
  21. Mark
    Posted on October 16, 2012 at 20:45 Permalink

    Great work, Manos!

    Is there any chance, that you’ll update the script to use horizontal and vertical scrollbars both on one div?

    Or may be someone already modified it in such way?

    Reply
    • malihu
      Posted on October 17, 2012 at 01:46 Permalink

      No plans at the moment but you never know πŸ™‚

      Reply
  22. Sean
    Posted on October 16, 2012 at 17:44 Permalink

    Is it possible to apply this scrollbar to the body?

    I’m trying this, but not having any luck:

    (function($){
    $(window).load(function(){
    $(“body”).mCustomScrollbar({
    scrollEasing: false,
    set_width:false,
    set_height:false,
    scrollButtons:{
    enable:true
    }
    });
    });
    })(jQuery);

    Reply
  23. Tobias Lopez
    Posted on October 16, 2012 at 15:39 Permalink

    hi,

    i’ve got something like this: http://cssdeck.com/labs/collab/lxdo1dqq/0

    i want to scroll in the generated content.
    is there an option?

    Thanks πŸ™‚

    Reply
  24. Simon Ebner
    Posted on October 15, 2012 at 23:29 Permalink

    Somehow it doesn’t work for me on Windows 7 with Chrome 22.0.1229.94 anymore. It used to work out fine but stopped from one day to another. I uploaded a picture, but I guess it’s not much help.

    I don’t get any error / warnings in the console. All scripts are loaded. $.fn.mCustomScrollbar is defined and I’m not experiencing js-related problems on any other page.

    Reply
    • malihu
      Posted on October 16, 2012 at 01:40 Permalink

      It works fine on me. Can you check it on another pc? Seems the plugin detects your chrome as a touch device. Did you attached any touch-screen monitors to your computer recently?

      Edit: The link you provided is probably the wrong one πŸ™‚

      Reply
      • Simon Ebner
        Posted on October 16, 2012 at 19:18 Permalink

        πŸ˜€ No idea how that could happen, but pretty funny though. Here’s the actual link: http://bit.ly/QPAMP7

        My laptop is a tablet computer, so it has a touch sensitive screen. However, the scrollbars worked fine in the past. Is there any way I can force the plugin to display the scrollbars?

        Reply
        • malihu
          Posted on October 17, 2012 at 01:54 Permalink

          Ah, that’s the cause. It detects its touch-screen.
          To force displaying the scrollbars, you need to edit jquery.mCustomScrollbar.js.
          Find the line (39):
          $(document).data("mCS-is-touch-device",true);
          and change it to:
          $(document).data("mCS-is-touch-device",false);
          Doing this of course will make your scrollbars stop working on other touch devices.

          Reply
  25. Dotred
    Posted on October 15, 2012 at 16:21 Permalink

    Great plugin! Works flawlessly thanks very much!

    Reply
  26. Pidz
    Posted on October 15, 2012 at 15:08 Permalink

    Hello Malihu !
    Your plugin is very great ! I love it.
    But I have a bad news, it don’t work with the new jquery UI 1.9.

    Be strong for that and have a good day.

    Reply
    • malihu
      Posted on October 15, 2012 at 18:02 Permalink

      I’ve tested it with jQuery UI 1.9.0 and it does work. Maybe your script isn’t loaded? Do you get any console errors?

      Reply
  27. Vipul Pradhan
    Posted on October 15, 2012 at 05:05 Permalink

    Hi Manos,

    I used this scrollbar in one of my projects which is still under development. While this works perfectly inside a div, I’ve been facing problems implementing it inside jQuery tabs.

    My HTML:
    <div class="allTabs"> <ul> <li><a href="#tabOne">ONE</a></li> <li><a href="#tabTwo">TWO</a></li> <li><a href="#tabThree">THREE</a></li> <li><a href="#tabFour">FOUR</a></li> </ul> <div id="tabOne"> <p>My Normal Text on First Tab</p> </div> <div id="tabTwo"> <p>My Normal Text on Second Tab</p> </div> <div id="tabThree"> <p>My Normal Text on Third Tab</p> </div> <div id="tabFour"> <p>My Lengthy Text on Left Half of Fourth Tab</p> <img class="myImage" src="my/image/url" width="320" height="400" /> <!-- This image on Right Half of Fourth Tab --> </div> </div>

    JQuery Tabs script I am using: http://papermashup.com/simple-jquery-tabs/

    Your JQuery script:
    <script> (function($){ $(window).load(function(){ $(".allTabs").mCustomScrollbar(); }); })(jQuery); </script>

    I have tried using “#tabFour” instead of “.allTabs” but my content just disappears and nothing happens.

    I have also tried to implement some of the solutions, reading from comments and looking on both the pages. But unable to do this since I am a total newbie when it comes to jquery and javascripts.

    I will want to use this scrollbar inside many sections that will have tabs.

    Can you please help?

    Reply
    • malihu
      Posted on October 15, 2012 at 06:03 Permalink

      Hello,

      The tabs plugin you’re using was not created to be used with other plugins, as it manipulates all divs inside it. You need to make some modifications in its js and css (e.g. changing .allTabs div to .allTabs>div) to make it work.

      I’ve made a quick working demo that applies custom scrollbars on each tab content:
      http://manos.malihu.gr/tuts/custom-scrollbar-plugin/tabs_temp_demo.html

      View its source to see the modifications in the code.

      Reply
      • Vipul Pradhan
        Posted on October 18, 2012 at 09:32 Permalink

        Thank you very much, Manos.
        After fiddling and trying various combinations, I was able to make the scrollbars appear inside all tabs by using > between all of the class and child elements in the css.
        Now, I need to try it the way I want i.e. all tabs will have scrollable text on left half and an image on the right half.
        A BIG THANK YOU AGAIN.
        πŸ™‚

        Reply
  28. Cristina
    Posted on October 14, 2012 at 16:01 Permalink

    Hello,
    I am experiencing a difficulty with the jQuery content scroller. If the content contains any links with ID or name attributes, the links will not work. How can I fix it? It’s really important for me…

    Reply
    • malihu
      Posted on October 15, 2012 at 03:21 Permalink

      Hi,
      If you want to scroll to specific position within your content, please see Methods: scrollTo section of the post.

      Reply
      • Cristina
        Posted on October 15, 2012 at 09:28 Permalink

        Hello, thanks for your reply. The problem isn’t so much with scrolling to a specific point of the page but in the links in it (only the ones linking into the same page; for example, <a href="#link.html">link</a>) which no longer work once I add the scrollbars; links to external pages work fine, but since I have several callbacks in the same pages, I need to figure out a way to make it work…
        Sorry for my bad English but I am italian! Hope it’s still understandable, though

        Reply
      • Cristina
        Posted on October 15, 2012 at 20:49 Permalink

        I’ve put up an example here
        http://misteridirapallo.altervista.org/scrollswlinks.html
        As you can see, links within the div to which scrollbars are applied do not work, whereas the link to an external page works fine. Thing is, I plan to have several cross-links within the selfsame pages. Is there a way I can make this work?

        Reply
        • malihu
          Posted on October 16, 2012 at 01:34 Permalink

          Yes, that’s why I suggested checking Methods: scrollTo section. You need to do it via javascript.

          In your page for example, to have LINK # 1 scroll to <a name="par3">porta</a>, you have to insert the following code below mCustomScrollbar function:

          $(".mistpage a[href='#par3']").click(function(e){ e.preventDefault(); $(".mistpage").mCustomScrollbar("scrollTo","a[name='par3']"); });

          You can do the same for each of your links or you can create a single function that gets anchors href value and targets the anchors with same name attribute values.

          Hope this helps

          Reply
          • Cristina
            Posted on October 16, 2012 at 14:15 Permalink

            Tried it in local and it works, thanks you so much! πŸ™‚

            Another thing – it’s possible to get the same results, but with links that are external to the page with the scrollbars (ie, a link outside the iframe, but that also scrolls to porta on click), and if so how?

            Also, I have an unrelated question – I’m trying to use the scrolls in a page that uses another JS (a comment box from a third party website), though curiously it seems to work on an on-and-off basis in Firefox and Opera (while perfectly in Chrome, IE8 and Safari). The developer of the box asked me if it was possible to delay the scrollbars initialization of a few seconds until the other widget is loaded. Now correct me if I’m wrong but I seem to understand it’s what the Update method does, right?… So I should put the widget’s code within append? Just want to make sure I understood correctly what I’m doing πŸ™‚

        • malihu
          Posted on October 16, 2012 at 16:12 Permalink

          You have your jQuery code inside the page which is loaded into the iframe, so it’s going to be tricky. You could probably use something like $("#my-id", parent.document.body) to target an anchor with id value “my-id” outside of the iframe:
          $("#my-id",parent.document.body).click(function(e){ e.preventDefault(); $(".mistpage").mCustomScrollbar("scrollTo","a[name='par3']"); });
          Haven’t tested this, so I can’t really say it works.

          The update method updates the scrollbar according to the new/updated content. So if another plugin manipulates content, you should call the update method after the changes are done.

          You can try calling the mCustomScrollbar after other plugin calls, so it attaches the scrollbar last (after other plugins do their thing). Note that after the custom scrollbar is attached on an element, its actual content resides inside the .mCSB_container div, meaning that you can target its content (without messing with custom scrollbar markup) by $(".mistpage .mCSB_container")

          Reply
          • Cristina
            Posted on October 16, 2012 at 21:22 Permalink

            Tested the external links and works perfectly on simple text links, not on the menu but I guess it’s something to do with the dynamic menu I’m using (instead of calling back the item with the id, as the text link does, it loads the whole parent page within the iframe). But it’s no big deal since the contents are reacheable from within the pages themselves, so I’ll just remove the external links to the sections and leave the ones that take to the pages πŸ™‚

            As for the page with two JS… I tried using update method, now it lets the other JS load fully, but then the scrolls themselves don’t o.O Did I make some mistake with the code? This is what I have so far;

            (function($){ $(window).load(function(){ $(".mistpage").mCustomScrollbar({ scrollButtons:{ enable:true } }); }); $(".mistpage .mCSB_container").append("<span style="display:none;">***</span>"); $(".mistpage .mCSB_container").append("<script type="text/javascript" language="javascript" id="pnyxeDiscussItInitJs450467">try { var zpbw_webWidgetClientKey = "AyvGQA3IXXSCbbQ3Di49Jg"; var pnyxeDiscussIt = new PnyxeDiscussIt(); pnyxeDiscussIt.init("450467"); } catch (e) {}</script>"); $(".mistpage .mCSB_container").mCustomScrollbar("update"); })(jQuery);

  29. MediaPod
    Posted on October 14, 2012 at 14:54 Permalink

    Hi and first of all : pretty good job here.

    Just wanted to ask a new functionnality. Your plugin works with touch devices, but unfortunately we can’t configure the way it works on them ( easing, no buttons appearing, etc…)

    There is one jQuery that does the job but, it does not fit to my project because this one place the rail and cursor inside the page body ( which does not work in “fixed” situation).

    https://github.com/inuyaksa/jquery.nicescroll

    Do you think it might be possible?

    best regards

    Reply
    • malihu
      Posted on October 15, 2012 at 04:10 Permalink

      Hello and thanks for the feedback.

      At the moment there’s way too much fragmentation between mobile OS, versions and browsers to apply a single solution that would work well in each and all of them. For this reason, I decided to let mobile OS/browser to handle the scrolling of divs (since each one does its own thing).

      I also didn’t want to stray away on how users scroll on touch devices by creating another non-native way of scrolling. For example, buttons scrolling is good for cursor but not so much for finger, simply because users are use to scroll by touch-and-swipe on their phones and tablets.

      If at some point mobile browsers mature enough I might try implementing a non-native js scrolling with more options. Right now, there are mobile browsers that won’t even let you scroll divs other than the page itself (Opera, mobile IE etc.). Implementing overflow: auto on the div (the simplest of CSS properties) gave me headaches as it’s not supported by Android 2.x (the OS most phones use).

      Reply
  30. Luca Pontarelli
    Posted on October 12, 2012 at 13:51 Permalink

    hello!
    first of all, i want to say that is a great plugin πŸ˜‰

    then.. i want to tell my problem.. in that page http://lacullasulmare.com/?page_id=5 the scroll bar dose not scroll all the text content..

    do you know why?

    Reply
    • malihu
      Posted on October 12, 2012 at 19:15 Permalink

      Hello,
      When you dragger has a fixed size (like the rounded one in your page) you should set the autoDraggerLength option parameter to false (see Configuration section).
      For example:
      $(".content").mCustomScrollbar({ autoDraggerLength:false });

      Reply

Comments pages: 1 20 21 22 23 24 85

Post a comment

Cancel reply

Your e-mail is never published nor shared. Required fields are marked *

You may use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
You can write or copy/paste code directly in your comment using the <code> tag:
<code>code here...</code>
You may also use the data-lang attribute to determine the code language like so:
<code data-lang-html>, <code data-lang-css>, <code data-lang-js> and <code data-lang-php>

css.php