Dheeraj Agrawal Dheeraj Agrawal - 4 months ago 22
jQuery Question

How to make custom scrollbar jQuery plugin

I was thinking to make custom scrollbar jQuery plugin, there are many plugins available for it but I want to make my own, problem is I am not getting the concept that how should I move a content by moving other div element (scrollbar) and also how should I move content by using mouse scroller??

Please help me to understand this.

Thanks

Answer

The easiest concept would be to use the jQuery UI draggable and attach the event .draggable() to the .scrollbar

enter image description here

jsBin demo

You just have to turn this couple of lines into a plugin.

jQuery/jQueryUI:

var $scrollable = $('.scrollable'),
    $scrollbar  = $('.scrollbar'),
    H   = $scrollable.outerHeight(true),
    sH  = $scrollable[0].scrollHeight,
    sbH = H*H/sH;

 $('.scrollbar').height( sbH ).draggable({
    axis : 'y',
     containment : 'parent', 
      drag: function(e, ui) {
            $scrollable.scrollTop( sH/H*ui.position.top  );
    }
}); 

$scrollable.on("scroll", function(){
    $scrollbar.css({top: $scrollable.scrollTop()/H*sbH });
});

HTML:

<div class="parent">    
    <div class="scrollbar"></div>    
    <div class="scrollable">
        Lorem ipsum dolor sit amet... looong text...
    </div>
</div>

CSS:

.parent{
    position:relative;
    margin:50px;
    overflow:hidden;
    height:200px;
    width:180px;
    background:#ddd;
}
.scrollable{
    overflow-y:scroll;
    position:absolute;
    padding:0 17px 0 0; /* play with this line */
    width: 180px;
    height:100%;
}
.scrollbar{
    cursor:n-resize;
    position:absolute;
    overflow:auto;
    top:0px;
    right:0px;
    z-index:2;
    background:#444;
    width:17px;
    border-radius:8px;
}

The above is just an example with the needed logic and math involved,
it misses the "hide-scrollbar", just to keep it simple. I'll leave to you to add all the needed tweaks, addons.

(old example: http://jsfiddle.net/roXon/FKzxa/)

Comments