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 overflowed with recommendations not to change the habitual type of controllers, it is increasingly necessary to encounter the customer's desire to see on his website an unusual, beautiful, and sometimes simply repainted scrollbar.

For example, this:

A task

Implement a vertical scrollbar that meets the following requirements:

    * conformity to the design;
    * Cross-browser compatibility;
    * the ability to scroll with the mouse wheel.

Decision

We will not reinvent the wheel, the good people have already worked for us. We use the free plug-in jScrollPane - it fully meets the listed requirements.

With its help, you can do this such a scroll or this.

Checked in:

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

To whom it is not enough, it is possible to look at other examples on an official page of a plug-in.

What to rock?

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 HTML container for the scroll:

<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 up the container design:

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

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

The last step is to initialize the script with the script:

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

And now about everything in detail

Learn more about HTML

In the example above, two containers are created: scroll-pane and scrollBox, and only scroll-pane is actually used. Why do I need an external scrollbox? It is useful for positioning the scrolling area, since it's rather difficult to position the scroll-pane itself, because the script will wrap it with its own container. Generally speaking, using an external diva (we have a scrollBox) for positioning is a tip from the official site of the plugin.

Learn more about CSS

A detailed 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>

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 the stylish scroll and restores the standard.

JScrollPane ()

Function name Description of function Data type
scrollbarWidth the width of the custom scrollbar in pixels. The default value is 10 int
scrollbarMargin Indents to the left of the scroll bar in pixels. Default value is 5 int
wheelSpeed Indicates how fast the mouse wheel will make the content scroll in pixels. The default value is 18 int
showArrows Indicates whether to display the arrows on the scroll bar. The default value is false. boolean
arrowSize height arrows if showArrows = true (if not specified, calculated from CSS) int
animateTo Whether animation is necessary at a call scrollTo and scrollBy. The default value is false. boolean
dragMinHeight The minimum height at which you can drag the slider. Default value is 0 int
animateInterval The interval in milliseconds for updating the scrollPane animation. The default value is 100 int
animateStep The distance that the slider passes in one step of the animation. The default value is 3 int
maintainPosition If you want the scrollbar to retain its position when it is re-initialized, then it will not scroll when you add more content. The default value is true boolean
scrollbarOnLeft Specifies that the scroll bar should appear to the left of the content (make sure that CSS also reflects this point) boolean
reinitialiseOnImageLoad Should the script be automatically reinitialized when images are loaded in the content. The default value is false. boolean

A little about the dynamics

In case the width (height) of the 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

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

Nuance with a scrolling mouse wheel

JScrollPane has one interesting feature. If you scroll with the mouse wheel, then after the entire content of the container is scrolled, the main page scroller starts spinning (of course, if it is available).

Judging by the code jScrollPane.js this is done specially (which means it's not a bug but a feature). But if this feature hinders, you can easily turn it off.

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

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

Change the return! DragOccured; on return false;

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

Scrolling to the desired position (update 1.08.10)

Sometimes it is required at once (or for some action) to scroll the 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 (counting from the upper border of this block with scrolling) or set 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

The functions cling to the block on which the scrolling was initialized.

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

I will draw your attention to the fact that "[0]" is mandatory. Why is it - I do not know (wishing to learn to dig the code of the plug-in), but without it does not work.

Pros:

    * works well in all popular browsers;
    * allows you to flexibly configure the appearance and behavior of the scroll;
    * Scroll with the mouse wheel.

Minus:

    * Horizontal scrolling is not implemented.