ReoCro
ReoCro

Reputation: 33

How to get direction of draggable div when grid is on?

Hello I'm trying to get the direction of the draggable div on drag when grid is on. So when i drag the div the direction or position left is logged by the mouse move and not when the grid is done on the div. So I want to know the direction of the div when the grid is done I mean when the div is dragged for the grid value. Is it possible to get that? Thanks!

Here is my JSFiddle:

https://jsfiddle.net/36z1pj2f/

Code:

$(".draggable2").draggable({
    grid: [10, 10],
    start: function(event, ui) {
         this.previousPosition = ui.position;
    },
    drag: function(event, ui) {
         var test = ui.position.left;

         console.log("test", test);

         var direction = (test > this.previousPosition.left) ? 'right' : 'left';
         console.log('moving ' + direction)

         this.previousPosition.left = test;
     }
});

Upvotes: 1

Views: 640

Answers (1)

Twisty
Twisty

Reputation: 30893

Try adding in the grid offset to your statement. This way you only test when the drag has crossed a tile (grid are).

Example: https://jsfiddle.net/Twisty/36z1pj2f/1/

jQuery

$(".draggable2").draggable({
  grid: [40, 40],
  start: function(event, ui) {
    this.previousPosition = ui.position;
  },
  drag: function(event, ui) {
    var grid = $(this).draggable("option", "grid");
    var leftOff = grid[0];
    var topOff = grid[1];
    var test = ui.position.left;
    var direction;
    if (test + leftOff < this.previousPosition.left) {
      direction = "Left";
      this.previousPosition.left = test;
      console.log('moving ' + direction)
    } else if (test - leftOff > this.previousPosition.left) {
      direction = "Right";
      this.previousPosition.left = test;
      console.log('moving ' + direction)
    } else {
      direction = "none";
    }
  }
});

Upvotes: 1

Related Questions