How can the axis be set depending it's draggable direction (after init)?
If it's dragged left-right it will be x, y if dragged up-down.
$("#belt").draggable({
handle: "li",
axis: "y",
start: function() {
//I want to be dragged in the axis i belong which should be x....
},
});
How can the axis be set depending it's draggable direction (after init)?
If it's dragged left-right it will be x, y if dragged up-down.
$("#belt").draggable({
handle: "li",
axis: "y",
start: function() {
//I want to be dragged in the axis i belong which should be x....
},
});
Share
Improve this question
edited Mar 2, 2012 at 2:14
Codex73
asked Mar 2, 2012 at 2:03
Codex73Codex73
5,77613 gold badges58 silver badges77 bronze badges
2 Answers
Reset to default 7You use distance to constrain the motion initially to get the initial read of which direction the user is moving and then set the axis limitation.
var x, y;
$("#belt").draggable({
start: function(event) {
x = event.originalEvent.pageX;
y = event.originalEvent.pageY;
},
drag: function(event) {
if (x && y) {
axis = Math.abs(event.originalEvent.pageX - x) > Math.abs(event.originalEvent.pageY - y) ? 'x' : 'y';
$("#belt").draggable('option', 'axis', axis);
x = y = null;
}
},
stop: function() {
x = y = null;
$("#belt").draggable('option', 'axis', false);
},
distance: 20
});
Here's a fiddle: http://jsfiddle/jhchen/B7J2E/
Appreciate the answer jhchen! I forked your fiddle to include some code so that the axis locking happens only when the user presses and holds the shift key while dragging.
http://jsfiddle/B7J2E/40/
var x, y;
$("#test").draggable({
start: function(event) {
console.log(event);
x = event.originalEvent.pageX;
y = event.originalEvent.pageY;
console.log(x, y);
},
drag: function(event) {
if (event.shiftKey) {
if (x && y) {
axis = Math.abs(event.originalEvent.pageX - x) > Math.abs(event.originalEvent.pageY - y) ? 'x' : 'y';
$("#test").draggable('option', 'axis', axis);
x = y = null;
}
}
},
stop: function() {
x = y = null;
$("#test").draggable('option', 'axis', false);
},
distance: 20
});