Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detect when item is being dragged left or right with jQuery UI's draggable?

I am using JQuery UI to make an element draggable and in the code, one can specify what to do on start, drag, and end.

But how can I run one function on drag left and another on drag right?

I have already limited the draggable axis to the x-axis only. So the element can only move left or right.

like image 596
Irfan Mir Avatar asked Apr 30 '13 06:04

Irfan Mir


2 Answers

Check this demo: http://jsfiddle.net/3NtS9/

You can do it by checking against the previous event coordinate on each atomic drag operation.

var prevX = -1;

$('div').draggable({
    drag: function(e) {
        //console.log(e.pageX);
        if(prevX == -1) {
            prevX = e.pageX;    
            return false;
        }
        // dragged left
        if(prevX > e.pageX) {
            console.log('dragged left');
        }
        else if(prevX < e.pageX) { // dragged right
            console.log('dragged right');
        }
        prevX = e.pageX;
    }
});
like image 99
techfoobar Avatar answered Oct 17 '22 04:10

techfoobar


Here's an easier way to do it:

$( "#draggable" ).draggable({
    drag: function( event, ui ) {
        $(this).text(ui.originalPosition.left > ui.position.left ?  'left' : 'right');
    }
});

Demo: http://jsfiddle.net/GNHTW/

like image 21
Ayman Safadi Avatar answered Oct 17 '22 04:10

Ayman Safadi