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?
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'))
}
});
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...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With