JScrollPane. Make beautiful scrolling

In spite of the fact that the Network is full of 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, since clever people have already worked for us. We use the free plug-in jScrollPane - it fully meets the listed requirements.

With it, 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, to use 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 scroller 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 cause the content to 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. The 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 scroll bar 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 the 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 by

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

Nuance with a scroll wheel mouse

JScrollPane has one interesting feature. If you rotate the 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 it's done specially (so it's not a bug and 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 (count from the top 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 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'll 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 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.