Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 930
Agorilla Avatar asked Apr 23 '11 19:04

Agorilla


2 Answers

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.

like image 189
James Montagne Avatar answered Nov 20 '22 06:11

James Montagne


ES6 version/Vanilla JS of https://stackoverflow.com/a/5839943/145122

let el = document.querySelector("#yourhtmlelement");
let x = 0, y = 0, top = 0, left = 0;

let draggingFunction = (e) => {
    document.addEventListener('mouseup', () => {
        document.removeEventListener("mousemove", draggingFunction);
    });

    el.scrollLeft = left - e.pageX + x;
    el.scrollTop = top - e.pageY + y;
};

el.addEventListener('mousedown', (e) => {
    e.preventDefault();

    y = e.pageY;
    x = e.pageX;
    top = el.scrollTop;
    left = el.scrollLeft;

    document.addEventListener('mousemove', draggingFunction);
});
like image 21
Ives.me Avatar answered Nov 20 '22 05:11

Ives.me