markzzz markzzz - 20 days ago 6
jQuery Question

What's wrong with triggering mouseup within a drag?

I'm trying to disable jquery drag when I reach the edge of the container (constraints to the x-axis). Here's the code:

var draggable = $("#drag-draggable");
var draggableWidth = draggable.width();
var draggableParentWidth = $('#drag-wrapper').width();
draggable.draggable({
axis: "x",
containment: "parent",
drag: function (e, ui) {
if ((draggableRight = ui.position.left + draggableWidth) == draggableParentWidth) {
draggable.trigger('mouseup');
console.log("finished");
}
}
});


The fact is: when I reach the edge (left), the
mouseup
is triggered, but it thrown an error:
Uncaught TypeError: Cannot read property '0' of null(…)


Which stop the drag, resulting not complete (I can see some pixels to the left of the red box).

Why am I wrong?

Answer

Use this fiddle:

JS:

var draggable = $("#drag-draggable");
var draggableWidth = draggable.width();
var draggableParentWidth = $('#drag-wrapper').width();
draggable.draggable({
  axis: "x",
  containment: "parent",
  drag: function (e, ui) {
  var draggableRight = draggable.position().left + draggableWidth;
    if (draggableRight >= draggableParentWidth) {
    e.preventDefault();
      draggable.trigger('mouseup');
      console.log("finished");
      //e.stopPropagation();
    }
  }
});

draggable.on('mouseup',function(){
console.log('hit');
});