Handle click and drag movement to scroll horizontally with mootools or jquery

Agorilla picture Agorilla · Apr 23, 2011 · Viewed 18.3k times · Source

Is there an easy way to handle the movement event composed of click and drag to the left or to the right on a div, in order to do a classic slider.
The idea is to do something similar to the scrolling of iphone apps but with left mouse click.

Answer

James Montagne picture James Montagne · Apr 30, 2011

You mean something kind of like this?

var x,y,top,left,down;

$("#stuff").mousedown(function(e){
    e.preventDefault();
    down = true;
    x = e.pageX;
    y = e.pageY;
    top = $(this).scrollTop();
    left = $(this).scrollLeft();
});

$("body").mousemove(function(e){
    if(down){
        var newX = e.pageX;
        var newY = e.pageY;

        $("#stuff").scrollTop(top - newY + y);    
        $("#stuff").scrollLeft(left - newX + x);    
    }
});

$("body").mouseup(function(e){down = false;});

http://jsfiddle.net/AhC87/2/

Click inside the area and drag to move around the div. It's quick and dirty, but if that was what you were meaning, it's a good starting point. Unless there's an existing plugin somewhere.