Scroll by clicking and dragging inward the div, instead of pressing the scroll button

This CSS is for DIV in MVC2 application. An automatic overflow line adds a horizontal scrollbar to the div, which is necessary since the table in the div is very wide and extends beyond 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 */ } 

In the end, several tables will be collected, and the horizontal scroll bar will be below the bottom of the screen.

Is there a way to allow users to click and drag into a div to make it scroll rather than actually click on the scroll bar?

+4
source share
2 answers

A very minimal jQuery approach for applying this function:

 $.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, use:

 $(document).ready(function(){ $("#divToScroll").attachDragger(); }); 
+14
source

To do this, you need to implement three mouse event handlers in javascript:

  • The mousedown handler must initiate a drag start by enabling the mousemove event handler (see 2)
  • The mousemove handler should display the vertical mouse position in the scrollTop div property
  • The mouseup handler should cause the drag to stop by disabling the mousemove event handler.

Please note: I do not think this is a good user interface design: you basically remove the ability to select text inside this div. In addition, the user can scroll with the mouse wheel, so I do not see the need for this.

+1
source

All Articles