0

I have a drag UI I'm creating, and I need to be able to disable anchor tags following an HREF if the user clicks on an anchor tag, but then drags more than 25 PX. The drag sensor I have working, the problem is I cannot use .click() because the mousedown has already fired for the drag, and .mouseup() seems to be too late to the game, because the event is still firing.

How do I make the following code right?

$(document).mousemove(function (e) {
  distance = e.pageX - initialPosition;
  $('#panorama').css({ 'left': distance });
  if (Math.abs(distance - 0) > 25) {
    //Event in question below:
    $('a').mouseup(function (e) { e.preventDefault(); });
  }
  return false;
});

1 Answer 1

1

It's hard to know what you are actually intending, but the moving to an anchor's destination occurs in the click event, not the mouseup event, so you'll need to handle the cancel there.

You'll also probably want to do the distance calculation in a click event, also, instead of waiting to register the handler until that threshold is passed, but that's your call.

You can view code that seems to deal with your situation here: jsFiddle

A lot of the code is to visualize the coordinates and the order of event triggers.

For posterity:

HTML

<a href="404.html">Link.....................................</a>
X:<span id='mouseX'></span>
Y:<span id='mouseY'></span>

JS

var initialPos = 0;

$('a').mousedown(function(e){
  updatePos(e);
  console.log('down');
  initialPos = e.pageX;
});
$('a').mousemove(function(e){
  console.log('move');
  updatePos(e);
});
$('a').click(function(e){
  console.log('click');
  updatePos(e);
  var distance = e.pageX - initialPos;
  if (Math.abs(distance) > 5) {
    console.log("Passed threshold, cancelling event");
    e.preventDefault();
    return false;
  }
});

function updatePos(e) {
  $('#mouseX').html(e.pageX);
  $('#mouseY').html(e.pageY);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Hey there! I think we're close, but something fishy is going on. Notice that in jsfiddle.net/7gHHS/17 the code still works, but I've left out all the event handling for .click(). I noticed that none of the click events show up in the console, and that after dragging my mouse for about 40 px on average, the tracking just stop so long as I'm inside mousedown. I tried using the code from jsfiddle.net/7gHHS/10 and it didn't work.
I think what you're seeing as "working" is the browser's default event for a dragged object on mousedown+move. If you do e.preventDefault() in the mousedown you'll see the browser still move to the next page when you mouse back up, requiring the click's preventDefault() again.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.