Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the direction of moving object in draggable plugin (jQuery)?

I have object (div-box), and it's draggable (I'm using jQuery). How I can get information which direction a visitor moved it? Example: User drag it to left down and I wanna know it, how?

like image 488
wokena Avatar asked Oct 05 '10 05:10

wokena


3 Answers

how about this?

var start,stop;

$("#draggable2").draggable({
    axis: "x",
    start: function(event, ui) {
        start = ui.position.left;
    },
    stop: function(event, ui) {
        stop = ui.position.left;
        alert('has moved ' + ((start < stop) ? 'right':'left'))
    }
});​

crazy fiddle

like image 61
Reigel Avatar answered Oct 19 '22 09:10

Reigel


The original position is built into the ui.helper object.. You can just do:

        $('#foo').draggable({
            stop: function(event, ui) {
                var dragged = ui.helper;
                var dragged_data = dragged.data('draggable');
                var direction = (dragged_data.originalPosition.left > dragged.position().left) ? 'left' : 'right';

                console.log(direction);
            }
        });

You can do this in the start, drag, or stop event callbacks...

like image 3
patrick Avatar answered Oct 19 '22 10:10

patrick


There is two answers to this question:

  1. get direction in real time, namely no matter the starting position. For that you need to set and use previousPosition as follow:

    
    $("#draggable").draggable({
        axis: "x",
        start: function(event, ui) {
            this.previousPosition = ui.position;
        },
        drag: function(event, ui) {
            var direction = (this.previousPosition.left > ui.position.left) ? 'left' : 'right';
            alert('moving ' + direction)
        }
    });​
    
  2. get direction after the drop, therefore using the starting position. For that you need to use the provided originalPosition as follow:

    
    $("#draggable").draggable({
        axis: "x",
        stop: function(event, ui) {
            var direction = (ui.originalPosition.left > ui.position.left) ? 'left' : 'right';
            alert('has moved ' + direction)
        }
    });​
    

Note: This code was written for and tested with jQuery 1.11.1

like image 1
barraq Avatar answered Oct 19 '22 09:10

barraq