Irfan Mir
Irfan Mir

Reputation: 2175

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.

Upvotes: 8

Views: 15822

Answers (3)

Ayman Safadi
Ayman Safadi

Reputation: 11552

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/

Upvotes: 9

basarat
basarat

Reputation: 276095

I would recommend you handle the start and stop events and determine the position delta in stop event to get whether it was moved left or right:

http://jqueryui.com/draggable/#events

Upvotes: 0

techfoobar
techfoobar

Reputation: 66693

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;
    }
});

Upvotes: 13

Related Questions