MrGuru
MrGuru

Reputation: 345

Only allow jQuery UI drag when mouse-movement is more horizontal than vertical

I have the axis of this jQuery UI draggable element set to x.

But it drags when the mouse is moving up an down over the element because the mouse movement is not exactly straight and there is a difference between the x coordinates. In other words the up / down mousemove while the mouse is done is slightly diagonal.

How can I get the element to only drag when the mouse is clearly moving left or right?

Or even better if the the difference between the x coordinates ( mouse down to current ) is larger or equal to the difference of the x coordinates.

I tried recording the event.pageX and event.pageY values on start of the dragging and then compare them by doing the absolute value at the start of dragging, so startPageX - current event.pageX >= startPageY - current event.pageY but that didn't seem to work.

EDIT: distance: 50 property sets a delay for 50px. Is there a way to set a delay for the x axis separate that the delay for the y axis?

Upvotes: 0

Views: 1123

Answers (2)

James Mason
James Mason

Reputation: 4296

You can combine axis and distance, but you'll have to override how jQuery checks the distance to constrain it to your axis. Here's a jsFiddle, and the relevant code for jQuery 1.10

$.ui.draggable.prototype._mouseDistanceMet = function(event) {
  if (this.options.axis == 'x') {
    return Math.abs(this._mouseDownEvent.pageX - event.pageX) >= this.options.distance;
  } else if (this.options.axis == 'y') {
    return Math.abs(this._mouseDownEvent.pageY - event.pageY) >= this.options.distance;
  } else {
    return (Math.max(
        Math.abs(this._mouseDownEvent.pageX - event.pageX),
        Math.abs(this._mouseDownEvent.pageY - event.pageY)
      ) >= this.options.distance
    );
  }
}
$( "#draggable" ).draggable({axis: 'x', distance: 50});

Upvotes: 1

Ashima
Ashima

Reputation: 4824

use axis option like this:

$( ".selector" ).draggable({ axis: "x" });

aixs option constrains dragging to either the horizontal (x) or vertical (y) axis. Possible values: "x", "y".

Documented here : http://api.jqueryui.com/draggable/#option-axis

Upvotes: 1

Related Questions