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