Giter VIP home page Giter VIP logo

jquery-custom-scrollbar's Introduction

jQuery Custom Scrollbar

jQuery Custom Scrollbar is a jQuery plugin that lets you add fully customizable scrollbars to your sites. With the plugin you can apply any css styles you want to your scrollbars.

Features

  • vertical and horizontal scrollbars you can style your own way
  • scrolling by mouse dragging, mouse wheel, keyboard – just as you would with native browser scrollbar
  • touch scrolling on mobile devices (Android, iPhone and iPad)
  • a couple predefined skins showing you how to style scrollbars
  • simple api that lets you scroll programmatically and be notified about scroll events

Requirements

The plugin supports all major browsers: Chrome, Firefox, IE 7+.

To use the plugin you obviously need jQuery (it should work in jQuery 1.4 and later versions).

Download

You can download the latest version here

Demos

In demos folder of this repo, there are some example usages of custom scrollbar and its api. The demos are also available online here

Usage

First download and add jquery.custom-scrollbar.js and jquery.custom-scrollbar.css to your site.

Suppose you have a container on your site with some lengthy content and you want to make it scrollable:


<div class="container">
  <!-- Some lengthy content -->
</div>

Define it’s width and height (below some example size is used):


.container {
  width: 300px; // you can also use max-width
  height: 400px; // you can also use max-height
}

Add a skin class to your container:


<div class="container default-skin">
  <!-- Some lengthy content -->
</div>

In the example we use default-skin. Plugin comes with two other predefined skins: gray-skin and modern-skin. You are not limited to that and you can style scrollbar your own way.

Finally call this js code:


$(document).ready(function() {
  $(".container").customScrollbar();
});

If container content does not fit in those sizes scrollbar will appear.

The above method will add vertical scrollbar only. If you also want to add horizontal scrollbar, there is one more css step required:


.container .overview {
  width: 1000px;
}

This defines example total width of the scrolled content (not just the width of the visible part as in previous step).

Options

There are some options you can pass when initializing scrollbar:

Option Type Default value Description
animationSpeed Number 300 Speed of the animation of programmatic scrolling. It’s possible to edit it with setAnimationSpeed method. Animation speed equal to 0 means no animation.
fixedThumbHeight Number undefined By default thumb height (in case of vertical scrollbar) is calculated automatically depending on viewport and overview height but you can fix thumb height to your chosen pixel value by setting this option. Make sure to not set min-height in css if you set fixedThumbHeight because min-height has priority.
fixedThumbWidth Number undefined Option analogical to fixedThumbHeight but applied to thumbs of horizontal scrollbars.
hScroll Boolean true Indicates whether or not, horizontal scrollbar should be shown when it’s necessary.
preventDefaultScroll Boolean false When the scrolling event occurs (e.g. down arrow key, mouse wheel) and it doesn’t cause the scrollbar to move (e.g. because the scrollbar is in extreme position), the event is propagated further which will cause the parent container to scroll. If it does cause the scrollbar movement then such event is stopped from propagating further and the parent container won’t scroll. This default behaviour can be changed by setting preventDefaultScroll: true. It will cause the custom scrollbar to always stop scrolling event propagation no matter if the scrollbar changed or didn’t change its position.
skin String undefined A css skin class that will be added to the scrolled container. You can define it in html as well as here in options. Note that skin has to be defined in one of those ways.
swipeSpeed Number 1 Indicates how fast touch scroll should be. When you swipe your finger by x pixels the content will be scrolled by swipeSpeed * x pixels.
updateOnWindowResize Boolean false Indicates whether scrollbar should recalculate thumb size when window is resized. See demos/resize.html for an example.
vScroll Boolean true Same as above but applies to vertical scrollbar.
wheelSpeed Number 40 Indicates how fast mouse wheel scroll should be. When you make the smallest possible mouse wheel move, the content will be scrolled by wheelSpeed pixels.

For example:


$("#my-container").customScrollbar({
  skin: "default-skin", 
  hScroll: false,
  updateOnWindowResize: true
  })

API

There are some methods of the plugin you may want to call.

setAnimationSpeed(speed)

Changes programmatic scroll animation speed to the passed speed – an integer indicating how many milliseconds the animation should last.

It’s also possible to set the animation speed upon plugin initialization. By default it equals 300.

Note that you may use this method if want to have some scrolls animated and some without animation – to get rid of the animation just call it with 0.


$(".container").customScrollbar("setAnimationSpeed", 200)

scrollTo(element)

Scrolls viewport to a given element inside scrolled content. An element might be jQuery object or a selector string. To control animation speed use animationSpeed initialization option. Example usage:


$(".container").customScrollbar("scrollTo", "#some-element-inside-container")

scrollToX(x)

Sets horizontal scrollbar position to x pixels. x should be in range from 0 to scrolled content width. If it’s outside that range, content will be scrolled to the start or to the end. To control animation speed use animationSpeed initialization option.


$(".container").customScrollbar("scrollToX", 100)

scrollToY(y)

Sets vertical scrollbar position to y pixels. x should be in range from 0 to scrolled content height. If it’s outside that range, content will be scrolled to the start or to the end. To control animation speed use animationSpeed initialization option.


$(".container").customScrollbar("scrollToY", 200)

scrollByX(x)

Moves horizontal scrollbar by x pixels. x can be positive or negative.


$(".container").customScrollbar("scrollByX", 100)

scrollByY(y)

Moves vertical scrollbar by y pixels. y can be positive or negative.


$(".container").customScrollbar("scrollByY", 200)

resize(keepPosition)

Recalculates and sets sizes of all scrollbar components. Call this whenever your scrolled block changes its size and scrollbar becomes invalid. After you call it scrollbar is adjusted to new sizes of your block.

Use keepPosition parameter to decide if the scrollbar should stay in the same position (keepPosition == true) or change position (keepPosition == true) so that the thumb position change is proportional to the size change. The first case is useful if your container changes size and you want to show exactly the same content that was visible before size change. The second case is useful when you’re listening to window resize.


$(".container").customScrollbar("resize", true)

remove()

Removes all the DOM changes and event bindings added by the plugin.


$(".container").customScrollbar("remove")

Events

customScroll

Triggered whenever content is scrolled. Separate events are fired when vertical and horizontal scrollbar is moved.


$(".container").on("customScroll", function(event, scrollData) {});

Handler function takes two arguments. event is standard jquery event object. scrollData is an object with 3 fields holding scroll specific information:

  • scrollPercent – floating point number in range 0.0 to 100.0 indicating percentage position of the scrollbar
  • scrollDirection – string that can take following 4 values: left, right, up, down – indicates what direction the scrollbar was moved in
  • scrollAxis – string indicating which scrollbar was moved: X for horizontal scrollbar and Y for vertical scrollbar

You can also bind handler to that event when initializing scrollbar:


$(".container").customScrollbar({
  onCustomScroll: function(event, scrollData) {}
});

License

The plugin is released under MIT license.

jquery-custom-scrollbar's People

Contributors

ekzobrain avatar ip512 avatar mzubala avatar

Stargazers

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

Watchers

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

jquery-custom-scrollbar's Issues

Remove function issues

I am finding the remove functionality does not work properly.

As per the documentation this should remove the markup:

$(".container").customScrollbar("remove");

The issue is, it does not properly remove the added "overview" and "viewport" elements. Looking in the code the issue is the use of unwrap.

removeScrollbarComponents: function () {
this.removeScrollbar("vertical");
this.removeScrollbar("horizontal");
if (this.overviewAdded)
this.$element.unwrap();
if (this.viewPortAdded)
this.$element.unwrap();
},

unwrap removes what is wrapping the element not what the element is wrapping. Thus this function ends up removing elements above the container instead of removing viewport and overview elements.

Animate on resize

Hi,
Hey will it be possible to provide the animation speed option when re-sized. The scenario is, I am calling the resize function when the div is made visible (using slideUp and slideDown methods), so it feels very jumpy. I felt the animation speed is provided to the resize as well it would make it neat.
I tried to make changes to the code but could't achieve it :(.
It would be really helpful if you can let me know on how to proceed with it, or any other alternatives i can use.

Thanks
Chethan K

Mouse Wheel Not Working

Well tested on pc and mac. The mouse wheel is not working on chrome, firefox on pc. On mac, since it is trackpad you can't determine the mouse-wheel on it.

This is my setup:

<script> $(document).ready(function(){ $(".news-section").customScrollbar({ skin: "default-skin", swipeSpeed: 2, fixedThumbWidth: auto }); }); </script>

scrollToElement location (question)

Polish (author of this project are Pole):

Witaj,
wiem, iż nie jest to błąd, ale nie bardzo wiem jak inaczej się z Tobą skontaktować.
Zainstalowałem na stronie Twój pasek przewijania i praktycznie wszystko jest dobrze, ale chciałbym, aby funkcja "scrollToElement" przenosiła do tego elementu tak, aby był on na górze, a nie na dole. Patrzyłem trochę w kod JS, ale to nie moja działka i jak nie ma konkretnych wartości to nie ogarniam :)

Załączę Ci obrazki:

  • jak to wygląda po przeniesieniu:

1

  • jak chciałbym, aby to wyglądało:

2

Oraz fragment kodu: http://www.curseforge.com/paste/8339/

Z góry dzięki za pomoc,
Pozdrawiam

Resize Problem

I have a dynamically sized container in which I'm using customScrollbar. After dynamically resizing my container (and some other elements within), I call .customScrollbar('resize') (which is attached to an element within the container). The problem that I'm having is that the actual scroll height of the customScrollbar element is almost 2x the size it should be, meaning that there is always tons of extra white space at the bottom. This problem only seem's to occur when I'm hiding or showing a second customScrollbar element (not sure if it's related).

Option to control scroll speed

Hi,
First of all thanks for the great plugin. It will be really very helpful if you can let me know on how to add the animation speed when scrollTo or any other methods are used, for example,
$(".container").customScrollbar("scrollTo","200", "#some-element-inside-container");
where "200" is the animation speed of the scroll.

Thanks
Chethan K

scrollData doesn't have scrollDirection property

Docs says - scrollDirection – string that can take following 4 values: left, right, up, down – indicates what direction the scrollbar was moved in.

But scrollData doesn't contain scrollDirection. It contains direction.

Docs or code should be changed.

Unable to zoom in/out on mobile devices

Scrollbar plugin captures all multi-touch events and tries to handle them as scroll events, but not all of them are actually scroll events, zoom in/out is just a popular example. Why do you capture multi-touch events when real scroll multi-touch events actually produce mousewheel events, which are already captured?

On iPad all hover events are mixed and broken after $el.customScroll()

After a lot of time spent on this issue, mor than a motnh a was creating workarounds....
So basically, fixed
"document..."
to
"this.scrollable.$element[0]..."
on line 310, so it's like:
this.scrollable.$element[0].addEventListener("touchmove", this.documentTouchmove);

Problem is that adding event listener to all document can break all other scripts. And adding event to exact scrollable element (well, is'n it what required?) - works ok.

This issue broke my site on on iPhones (4\5) and iPads.
Nowhere else.

touch scroll using thumb

Glad that i've got a solution while i'm checking for a fixed thumb fancy scrollbar.

While I'm using this with my mobile device, i'm able to scroll on the content, but scrolling with thumb is not working.

If i'm clicking on the vertical track the content is getting scrolled to the ultimate bottom and to the ultimate top and also the thumb is getting scrolled to top and bottom. Scrolling the content with the thumb isn't working. Have i missed anything?

Issue with removeWindowResize

The function removeWindowResize has an issue in that it does not confirm that the method this.windowResize has been instantiated.

removeWindowResize: function () {
$(window).unbind("resize", this.windowResize);
},

this.windowResize gets defined based on an if statement in the initWindowResize method.

initWindowResize: function () {
if (this.scrollable.options.updateOnWindowResize) {
var _this = this;
this.windowResize = function () {
_this.resize();
};
$(window).resize(this.windowResize);
}
},

This means that it may not ever be defined. If this is the case and then the removeWindowResize is called when the second arguement gets passed to the unbind method it is 'undefined'. This results in jQuery treating the unbind method as if it did not have a specified handler. When unbind does not have a specified handler it unbinds everything on the targeted event. This is an issue that can be fixed by confirming this.windowResize is defined before unbinding it.

removeWindowResize: function () {
if (typeof this.windowResize == 'function'){
$(window).unbind("resize", this.windowResize);
}
},

Touch scrolling is too fast (fix)

If it helps anyone else; I found that the touch/drag scrolling speed was much faster than it would normally be in the browser (Google Chrome on touch-screen PC).

This can be fixed by just changing line 406:

this.moveScroll(event.touches[0], -1);

to:

this.moveScroll(event.touches[0], -this.ratio);

I haven't tested this on mobile devices as this was not relevant in my current project.

Fixed thumb size

I don't know if it's already possible, but I would like to give the vertical thumb a fixed height. When I do this, my thumb stops halfway the page and not at the end.

Could you make this possible to do?

Max-Height

If I put CSS 'max-height' attribute on a container (without height), scroller is not working.

Cheers

Wordpress Version

Hey,

Great plugin! Based on a client's need for a transparent scrollbar across their site, I've created a wordpress version of the plugin located here: https://github.com/kaynenh/custom-scrollbar.

I just wanted to make sure you were aware of my plugin. Since I didn't see a specific license, I also wanted to make sure you were okay with it.

Thanks again!

Scroll not working with CSS Transform Scale on Firefox

I have a DIV that's scaled back to about 0.65. In doing so, custom scroll won't work. It simply doesn't scroll at all. The issue is very similar to this user's problem on SO (diff plug-in), however for me the scroll bar just flickers and doesn't do anything.

http://stackoverflow.com/questions/20093804/custom-javascript-scrollbars-jscrollpane-with-transform-scale-error

Any ideas? Love your script, but may have to switch if this can't be fixed.

Increasing scroll speed

Is there a way by which I can play around with the scroll speed, the default one is too slow.

Official copyright notice missing

Hi,

Thank you for the great scrollbars! I want to use this plugin in my web site and I know this plugin is published under the MIT license, but I could not find the copyright notice.

According to MIT License http://opensource.org/licenses/MIT

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

So, I think an official copyright notice is required to use the great plugin.
Could you provide it?

Keyboard scroll fires even when element is not focused and hovered by another element

For keyboard scroll to work keydown and mousemove events are bound to the DOM and mouse position is determined with the help of isMouseOver() function, the logic of which is very pure because element may be hovered by some overlay, but it will still be subject to scrolling. I think logic should be like this: we capture mouseover/mouseout events (with jQuery hover() method) on scrollable element and when it is hovered - we start capturing keydown events on document. When element recieves mouseout - we remove keydown listener, because there's no need to capture theese events then. Also, keyboard scroll should be disabled when form elements recieve focus inside scrollable area, because they also use up/down keyboard buttons and container shouldn't be scrolled then. And this functionality should be totally disabled for mobile devices, because they don't have any keyboard anyway :) there's only one way of scrolling - touch.

Autohide

Hi,

I have another feature idea, which should be pretty simple and cool.

Add a class to scrollbar-thumb only while scrolling and remove when done with scrolling.

It then would be possible to only make the scrollbar-thumb only visible while scrolling, like for example on a mac. With css transition it would go nice and smooth :-)

.thumb {
opacity:0;
transition: opacity .5s;
transition-delay: 0s;
}
.thumb.new_class_added_on_scrolling {
opacity:1;
transition: opacity 2s;
transition-delay: 2s; /* hide thumb with a delay of 2 seconds */
}

Tobias

touch scroll using thumb

Glad that i've got a solution while i'm checking for a fixed thumb fancy scrollbar.

While I'm using this with my mobile device, i'm able to scroll on the content, but scrolling with thumb is not working.

If i'm clicking on the vertical track the content is getting scrolled to the bottom and to the top and also the thumb is getting scrolled to top and bottom. Scrolling the content with the thumb isn't working. Have i missed anything?

Functions scrollByX(x) and scrollByY(y) not defined

Functions scrollByX(x) and scrollByY(y) mentioned in the documentation do not work. They are not defined in the .js file. The documentation appears to be wrong. What functions are to be called to programmatically scroll horizontally / vertically by N pixels?

Scroll bar not appearing on the page!

Hi,

I have added the lines of code to js & css and also called the custom scroll bar function over the selector, but it isn't working. On checking the chrome developers tool i was able to see that the scrollbar components/elements haven't even been added to the code. Could you help me out with this issue.

Wrong working on Google Chrome and Safari

Polish (author of this project are Pole):

Witaj,
pomyślałem sobie, iż posprawdzam sobie dzisiaj jak wygląda stronka, którą robię na innych przeglądarkach (oprócz IE - nie działa mi :/) i znalazłem pewien problem, a mianowicie na Google Chrome i Safari nie działa przypisywanie lokalnych stylów do pasków (np. wysokość, brak widoczności), co skutkuje również znacznym wolnym miejscem do przewijania pod faktyczną stroną.
W arkuszu stylów od Twojego paska zmieniałem tylko kolorystykę i ustawiałem brak animacji (transition normalnie używam do niektórych elementów na stronie) w stylu nowoczesnym i po zmianach na Operze (normalnie z niej korzystam) oraz na Firefoxie wszystko jest tak jak powinno.

Możliwe, iż ten błąd występuje tylko u mnie - może coś źle zrobiłem.
Zamieszczam zrzut ekranu z Google Chrome:
1

Liczę na odpowiedź w jaki sposób zaradzić tej niedogodności lub proszę o łatkę.
Pozdrawiam

MaxOverviewPosition

Could you put

calculateMaxOverviewPosition:function(){
return Math.max(0,this.sizing.size(this.scrollable.$overview)-this.sizing.size(this.scrollable.$viewPort))
}

Otherwise it's not working for me!!
Content moves to bottom, but i need it to stick to the top.

Think about it. I couldn't see any disadvantages, MaxOverviewPos should not be smaller than 0!

Thanks

Un-init method?

Hi,

I love your custom scrollbar script but as part of a responsive site I need the ability to completely remove any DOM changes or events that the script has added when moving between breakpoints. I was going to use this along side jRespond.

Would it be easy for you to add such a "un-init" function/method?

Background scroll

Hi,

I was the one suggesting the scroll in the background whenever the container itself is scrolled to the end.

Now it is always like that. Would you think about making this configurable (an option)?

I think in some cases it's really useful, in some it isn't!

Thanks
Tobi

updateOn parent resize feature

Thank you for the plugin!

I'd like to update when the parent of scrollable div is resized.
Is it possible to achieve this? (similar to updateOnWindowResize)

Thank you!

Let scroll through at the end

Hi, this is more an idea for a new feature, than an issue.

Wouldn't it be nice, if the main window would start scrolling as soon as the customscroll-container reached one of its ends?

It would help me a lot!

Thanks again for the great work.

Firefox scrolls also in background

Hi!

I have an issue with your plugin.

If I have a layer display fixed on which I scroll, the firefox main window also scrolls.

You can see an example at
https://findpenguins.com/demo-account/74576545/worldtrip
Just click on the statistics icon and then scroll.

It's only in firefox - btw same in a picture popup.

Apart from it's all real great work, I chose your plugin over all these big time others. I like it simple.

Thank you
Tobi

P.S. On more little thing, you should add something to the Function "calculateMaxOverviewPosition"

Instead of:
var y = this.sizing.size(this.scrollable.$overview) - this.sizing.size(this.scrollable.$viewPort);

Use:
var y = Math.max(0,this.sizing.size(this.scrollable.$overview) - this.sizing.size(this.scrollable.$viewPort));

Sometime it will get smaller than 0, and that we don't want :-)

Resize-Issue

Hi,
I think I found a bug, following case:

updateOnWindowResize is on.
The scrollpane adjusts its size together with the window height.


Some content with fixed height
Scrollpane with variable height

If I decrease the window height, so it is smaller or equals the fixed height of top content, the scrollpane stops resizing itself.

In other words, whenever the height of the scrollpane is 0px, it stops working/refreshing.

Could be some simple boolean bug.

scoll-bar margin

hello,

I love this project!
I want to give margin to .scroll-bar. so, I gave margin like this.

.scrollable.topfost-skin .scroll-bar.horizontal {
    margin: 0 10px;
}

then, .thumb move element out of parent..
how can I give margin?

thanks!

+ add

.scrollable.topfost-skin .scroll-bar.horizontal {
    border:1px solid #000;
}

when .scroll-bar has border, .scroll-bar's width included border width.
I think .scroll-bar width calculate code need to be change outerWidth().
if that the case, maybe outerWidth(true) do fix .scroll-bar's margin too.

Does not work when used in unordered/ordered list

I tried this one to customize the main navigation of my website but it does not work or never to work because the list items will get wrapped with div elements.

instead of this:

<ul>
<li>....
<li>....
</ul>

The plugin transform the html structure to this

<ul>
<div>
<li>....
</div>
</ul>

which result to break my navigation.

How to call multiple methods in scrollbar initializing?

Can we call more than one method in scrollbar initializing?

For example
I have to call scrollToY and ScrollToX parallely. I know there is scrollToXY method present here, that is not in my scope. We can do it like below, but it can initialize one method at a time.

$(".container").customScrollbar("scrollToY", 200);
//OR
$(".container").customScrollbar("scrollToX", 200);

Can I call something like below?

$(".container").customScrollbar({ scrollToX:  200, scrollToY: 150});

preventDefaultScroll and Firefox

Great plugin. I am testing this out and have found that when setting "preventDefaultScroll" to true, the expected function works in all browsers except Firefox. Firefox will scroll the page as you scroll the scrollable element.

Div content gets selected upon scroll.

If I clcik on scroller thumb and drag it down or top. the contnet in the div on which scroller is applied gets selected.

If you can help me in this regard It will be highly appreciable.

selection

Recommend Projects

  • React photo React

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

  • Vue.js photo Vue.js

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

  • Typescript photo Typescript

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

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

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

Recommend Topics

  • javascript

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

  • web

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

  • server

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

  • Machine learning

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

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

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

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.