This page has been robot translated, sorry for typos if any. Original content here.

JScrollPane. Make beautiful scrolling

Despite the fact that the Network is overwhelmed with recommendations not to change the usual type of controllers to the user, it is increasingly necessary to encounter the customer’s desire to see on its website an unusual, beautiful, and sometimes just repainted scrollbar.

For example, such:

Task

Implement a vertical scrollbar that meets the following requirements:

    * compliance with the design;
    * cross-browser compatibility;
    * the ability to scroll with the mouse wheel.

Decision

We will not reinvent the wheel, since smart people have already worked for us. We use the free jScrollPane plugin - it fully meets the listed requirements.

With it, you can make such a scroll or something like that.

Checked in:

    * IE 6-8 * Firefox 3 * Opera 9.5-10 * Safari 3

To whom a little, you can see other examples on the official page of the plugin.

What to download?

Fast start

We connect libraries and do not forget about CSS:

<code>&lt;link type=text/css rel=stylesheet href=css/jScrollPane.css /&gt;&lt;script type=text/javascript src=js/jquery-1.4.2.min.js&gt;&lt;/script&gt;&lt;script type=text/javascript src=js/jquery.mousewheel.min.js&gt;&lt;/script&gt;&lt;script type=text/javascript src=js/jScrollPane.js&gt;&lt;/script&gt;</code>

Create in HTML container for scrolling:

<code>&lt;div class=scrollBox&gt;&lt;div id=pane class=scroll-pane&gt;Хочу себе необычный скролл! &lt;/div&gt;&lt;/div&gt;</code>

In CSS we set the design of the container:

<code>.scroll-pane { width: 700px; /* Ширина видимой области*/ height: 275px; /* Высота видимой области*/ overflow: auto; /* Если отключены скрипты это правило позволит отобразить обычный скролл */ }</code>

Customize styles from jScrollPane.css and draw pictures (more on this below).

The last step is to initialize the scroll script:

<code>&lt;script type=text/javascript&gt;jQuery(function() { jQuery('#pane').jScrollPane({scrollbarWidth:18, showArrows:true}); }); &lt;/script&gt;</code>

And now more about everything

More about HTML

In the example above, two containers are created: scroll-pane and scrollBox, and in fact only scroll-pane is used. What is the external scrollBox container for? It is useful for positioning the scrolling area, since it is difficult to position the scroll-pane itself, because the script will wrap it with its own container. Generally speaking, using an external div (we have scrollBox) for positioning is the advice from the official site of the plugin.

More on CSS

Promised detailed analysis of jScrollPane.css:

<code>.jScrollPaneContainer { position: relative; overflow: hidden; z-index: 1; } /* Трек - полоса по которой бегает ползунок */ .jScrollPaneTrack { position: absolute; cursor: pointer; right: 0; top: 0; height: 100%; background: url(../images/scrollTrak.gif) repeat-y; /* задаем фоновую картинку или просто цвет фона */ } /* Средняя часть ползунка (резиновая, т.к. ползунок меняет высоту в зависимости от количества содержимого) */ .jScrollPaneDrag { position: absolute; background: url(../images/scrollDrag.gif) repeat-y; /* задаем фоновую картинку или просто цвет фона */ cursor: pointer; overflow: hidden; left:1px; } /* верхушка ползунка (можно задать height:0, если ползунок не имеет выраженной верхушки) */ .jScrollPaneDragTop { position: absolute; top: 0; left: 0; overflow: hidden; background: url(../images/scrollDragTop.gif) no-repeat; /* задаем фоновую картинку или просто цвет фона */ height:3px; /* высота верхушки */ } /* низ ползунка (можно задать height:0, если ползунок не имеет выраженного низа) */ .jScrollPaneDragBottom { position: absolute; bottom: 0; left: 0; overflow: hidden; background: url(../images/scrollDragBot.gif) no-repeat; /* задаем фоновую картинку или просто цвет фона */ height:3px; /* высота низа */ } /* стрелка вверх (правило можно исключить, если скролл по дизайну без стрелок) */ a.jScrollArrowUp { display: block; position: absolute; z-index: 1; top: 0; right: 0; text-indent: -2000px; overflow: hidden; height: 18px; /* высота стрелки (ширина определяется шириной скролла при инициализации скрипта) */ background: url(../images/arrow_up.gif) no-repeat; /* задаем фоновую картинку или просто цвет фона */ } /* стрелка ввниз (правило можно исключить, если скролл по дизайну без стрелок)*/ a.jScrollArrowDown { display: block; position: absolute; z-index: 1; bottom: 0; right: 0; text-indent: -2000px; overflow: hidden; height: 18px; /* высота стрелки (ширина определяется шириной скролла при инициализации скрипта) */ background: url(../images/arrow_down.gif) no-repeat; /* задаем фоновую картинку или просто цвет фона */ }</code>

Read more about js

Two functions are defined:

jScrollPane initializes the scroll, according to the specified parameters (see the table below for a list).
jScrollPaneRemove "Deinitialization" - removes a stylish scroll and restores the standard.

JScrollPane Parameters ()

Function name Function description Data type
scrollbarWidth custom scrollbar width in pixels. The default value is 10 int
scrollbarMargin indents to the left of the scroll bar in pixels. The default value is 5 int
wheelSpeed indicates how fast the mouse wheel causes the content to scroll in pixels. The default value is 18 int
showArrows indicates whether the arrows on the scroll bar are displayed. Default is false boolean
arrowSize arrow height if showArrows = true (if not set, calculated from CSS) int
animateTo Do you need an animation when you call scrollTo and scrollBy. Default is false boolean
dragMinHeight the minimum height at which you can drag the slider. The default value is 0 int
animateInterval The interval in milliseconds to update the scrollPane animation. The default value is 100 int
animateStep The distance that the slider goes in one step of the animation. Default value 3 int
maintainPosition If you want the scroll bar to retain its position when reinitializing, then it will not scroll when adding more content. Default true boolean
scrollbarOnLeft Specifies that the scroll bar should appear to the left of the content (make sure the CSS also reflects this point) boolean
reinitialiseOnImageLoad Should the script automatically re-initialize when uploading images in the content. Default is false boolean

A little about the dynamics

In case the width (height) of a scroll changes dynamically, it is necessary to call the functions jScrollPaneRemove and jScrollPane sequentially.

Suppose we have this CSS:

<code>.scrollBox{ width:200px; } .scroll-pane { width: 100%; height: 100px; overflow: auto; }</code>

The script changes the width of the scrollBox, thereby automatically changing the width of the .scroll-pane:

<code>&lt;script type=text/javascript&gt;jQuery('#more').click(function() { jQuery('.scrollBox').css('width','300px'); jQuery('#pane').jScrollPaneRemove(); jQuery('#pane').jScrollPane({scrollbarWidth:18, showArrows:true}); }); &lt;/script&gt;</code>

Demo example

Verified by

    * IE 6-8 * Firefox 3 * Opera 9.5-10 * Safari 3

Nuance with scrolling mouse wheel

JScrollPane has one interesting feature. If you turn the scroll wheel with the mouse wheel, then after the entire contents of the container scrolls, the main page scrollbar starts to spin (of course, if it is available).

Judging by the jScrollPane.js code, this was done on purpose (which means it is not a bug but a feature). But if this feature interferes, it can easily be turned off.

We climb into the jScrollPane.js code and find the lines there:

<code>$container.bind( 'mousewheel', function (event, delta) { ...тра-та-та многабукофф... return !dragOccured; } );</code>

Change return! DragOccured; to return false;

Everything! Now the wheel behaves more logically and will not control the main page scrolling until the mouse cursor moves out of the container.

Scrolling to the desired position (update 1.08.10)

Sometimes it is required immediately (or for some action) to scroll a block with such scrolling to a certain position. For this, the plugin has two (for some reason poorly described) functions:

scrollTo - scroll the content to the specified position. The position can be specified in px (count from the upper border of this block with scrolling) or set the id - the block will scroll to the element with the specified id

scrollBy - scroll the block by the specified number of pixels relative to the current position

Functions cling to the block on which scrolling initialization was hung.

<code>&lt;script type=text/javascript&gt;jQuery('#pane').jScrollPane({scrollbarWidth:18, showArrows:true}); jQuery('#pane')[0].scrollTo(500); &lt;/script&gt;</code>

I’ll draw your attention to the fact that "[0]" is a must. Why it is - I do not know (wishing to learn to dig the code of the plugin), but without this does not work.

Pros:

    * works adequately in all popular browsers;
    * allows you to flexibly customize the appearance and behavior of the scroll;
    * scrolled mouse wheel.

Minus:

    * Horizontal scrolling is not implemented.