Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll by clicking and dragging inside div instead of clicking scrollbar

Tags:

css

This CSS is for a DIV in an MVC2 application. The overflow:auto line adds a horizontal scrollbar to the div which is needed since the table in the div is very wide and extends past the edge of the page.

#main
{
    padding: 30px 30px 15px 30px;
    overflow:auto;/* this adds horizontal scroll*/
    background-color: #fff;
    margin-bottom: 30px;
    _height: 1px; /* only IE6 applies CSS properties starting with an underscore */
}

Eventually there are going to be multiple tables stacked and the horizontal scroll bar is going to be below the bottom of the screen.

Is there a way to allow the users to click and drag inside the div to make it scroll instead of actually having to click the scrollbar?

like image 515
Joshua Slocum Avatar asked Oct 05 '10 14:10

Joshua Slocum


2 Answers

A very minimized JQuery approach to apply this functionality:

$.fn.attachDragger = function(){
    var attachment = false, lastPosition, position, difference;
    $( $(this).selector ).on("mousedown mouseup mousemove",function(e){
        if( e.type == "mousedown" ) attachment = true, lastPosition = [e.clientX, e.clientY];
        if( e.type == "mouseup" ) attachment = false;
        if( e.type == "mousemove" && attachment == true ){
            position = [e.clientX, e.clientY];
            difference = [ (position[0]-lastPosition[0]), (position[1]-lastPosition[1]) ];
            $(this).scrollLeft( $(this).scrollLeft() - difference[0] );
            $(this).scrollTop( $(this).scrollTop() - difference[1] );
            lastPosition = [e.clientX, e.clientY];
        }
    });
    $(window).on("mouseup", function(){
        attachment = false;
    });
}

To apply it utilize:

$(document).ready(function(){
 $("#divToScroll").attachDragger();
});
like image 73
MKN Web Solutions Avatar answered Oct 24 '22 10:10

MKN Web Solutions


You need to implement three consecutive mouse event handlers in javascript for this:

  1. The mousedown handler should trigger a drag start by enabling the mousemove event handler (see 2)
  2. The mousemove handler should map the vertical mouse position to the scrollTop property of the div
  3. The mouseup handler should trigger a drag stop by disabling the mousemove event handler

Note that I don't think this is good user interface design: you're basically removing the ability to select text inside this div. Besides, the user can scroll using the mouse wheel, so I don't see the need for this.

like image 34
Peter Kruithof Avatar answered Oct 24 '22 11:10

Peter Kruithof