Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set axis depending draggable direction jQuery draggable

How can the axis be set depending it's draggable direction (after init)?

If it's dragged left-right it will be x, y if dragged up-down.

$("#belt").draggable({
    handle: "li",
    axis: "y",
    start: function() {

        //I want to be dragged in the axis i belong which should be x....

    },
});
like image 323
Codex73 Avatar asked May 26 '26 19:05

Codex73


1 Answers

You use distance to constrain the motion initially to get the initial read of which direction the user is moving and then set the axis limitation.

var x, y;

$("#belt").draggable({
    start: function(event) {
        x = event.originalEvent.pageX;
        y = event.originalEvent.pageY;
    }, 
    drag: function(event) {
        if (x && y) {
            axis = Math.abs(event.originalEvent.pageX - x) > Math.abs(event.originalEvent.pageY - y) ? 'x' : 'y';
            $("#belt").draggable('option', 'axis', axis);
            x = y = null;
        }        
    },
    stop: function() {
        x = y = null;
        $("#belt").draggable('option', 'axis', false);
    },
    distance: 20
});​

Here's a fiddle: http://jsfiddle.net/jhchen/B7J2E/

like image 117
jhchen Avatar answered May 28 '26 14:05

jhchen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!