How to get the direction of a moving object in a draggable plugin (jQuery)?

I have an object (div-box) and it is being dragged (I use jQuery). How can I get information about which direction the visitor visited? Example: a user dragged it to the left and I want to know how?

+3
source share
4 answers

how about that?

var start,stop;

$("#draggable2").draggable({
    axis: "x",
    start: function(event, ui) {
        start = ui.position.left;
    },
    stop: function(event, ui) {
        stop = ui.position.left;
        alert('has moved ' + ((start < stop) ? 'right':'left'))
    }
});​

crazy violin

+9
source

The starting position is built into the ui.helper .. object. You can simply do:

        $('#foo').draggable({
            stop: function(event, ui) {
                var dragged = ui.helper;
                var dragged_data = dragged.data('draggable');
                var direction = (dragged_data.originalPosition.left > dragged.position().left) ? 'left' : 'right';

                console.log(direction);
            }
        });

You can do this by starting, dragging or stopping events ...

+3
source

:

  • , . previousPosition :

    
    $("#draggable").draggable({
        axis: "x",
        start: function(event, ui) {
            this.previousPosition = ui.position;
        },
        drag: function(event, ui) {
            var direction = (this.previousPosition.left > ui.position.left) ? 'left' : 'right';
            alert('moving ' + direction)
        }
    });​
    
  • , . originalPosition, :

    
    $("#draggable").draggable({
        axis: "x",
        stop: function(event, ui) {
            var direction = (ui.originalPosition.left > ui.position.left) ? 'left' : 'right';
            alert('has moved ' + direction)
        }
    });​
    

: jQuery 1.11.1

+1

Source: https://habr.com/ru/post/1768001/


All Articles