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?
Asked
Active
Viewed 1.0k times
4 Answers
11
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

IAbstract
- 19,551
- 15
- 98
- 146

Reigel Gallarde
- 64,198
- 21
- 121
- 139
-
That's the gist of it. Implementation details may vary, but you'll have to remember where the cursor was previously and compare to where it is now. May also want to check if horizontal change was greater than vertical change to choose between left/right or up/down. – Brad Mace Oct 05 '10 at 05:54
-
Well, this is the start of the idea. `ui.position.top` is also available. The OP can deal with it easy. – Reigel Gallarde Oct 05 '10 at 05:56
3
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...

patrick
- 9,290
- 13
- 61
- 112
1
There is two answers to this question:
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) } });
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

barraq
- 326
- 2
- 7