0

I have a jQuery draggable element which should allow itself to be dragged up, down, or right, but not left.

Is there any way I can accomplish this?

I realize it's possible to use revert, check its position after being dragged, and bring it back to the starting position; however, I would like to disabled left-direciton dragging from the start.

This is my current code:

            $(elem).draggable({
                cursor: "move",
                scroll: false,
                addClasses: true,
                start: function(e, ui) {
                    //I can calculate the starting position here
                },
                stop: function(e, ui) {
                    //some stuff happens here, not relevant
                }
            });

My idea is to get the starting position and then somehow check the position while the dragging is going on dynamically, compare it to the starting one, and if current.left

Is this possible?

If not, then I guess I'll have to perform the check within the stop section of the code, and revert to the original position from there.

Note that I can't change the size/position of the parent container, which is full-screen. Also, if I move the draggable element right and drop it, I still should not be able to drag it left from the new position.

sveti petar
  • 3,637
  • 13
  • 67
  • 144
  • 1
    Possible duplicate http://stackoverflow.com/questions/15609776/restrict-drag-only-in-one-direction – Mokkun May 10 '17 at 09:30
  • @Mokkun I can't use "axis: y" because it would restrict movement to the right side as well. – sveti petar May 10 '17 at 09:33
  • This will need to be done in `drag`, to examine the position of the mouse or the edge of the item being dragged and determine if it has collided with a specific value. The other option is to create a container that meets your needs, and set `containment` options to use this element. – Twisty May 10 '17 at 15:20

1 Answers1

0

A simple example of how to do this in drag function:

https://jsfiddle.net/Twisty/ysuh8wgq/

JavaScript

$(function() {
  var elem = "#div1";
  var myStart;
  $(elem).draggable({
    containment: "parent",
    cursor: "move",
    scroll: false,
    addClasses: true,
    start: function(e, ui) {
      myStart = ui.position;
    },
    drag: function(e, ui) {
      if (ui.position.left < myStart.left) {
        return false;
      }
    },
    stop: function(e, ui) {
      //some stuff happens here, not relevant
    }
  });
});

You can also do this:

https://jsfiddle.net/Twisty/ysuh8wgq/2/

drag: function(e, ui) {
  if (ui.position.left < myStart.left) {
    ui.position.left = myStart.left;
  }
}

This will allow the user to continue to move the item, but can not longer push past that left value.

Twisty
  • 30,304
  • 2
  • 26
  • 45