javascriptjqueryswipedragjquery-draggable

Nested Drag, Swipe using jQuery


Folowing code is for nested swiping/dragging, parent and child both are draggable.

P1... It's working nice but with one lovely problem, if we drag the parent alone it works perfectly. But when we drag draggable child the parent also gets dragged automatically... Jsbin for P1...

P1... is caused by ".closest('.'+ mainElem[0].className)"; if i remove this then the parent does not get dragged while dragging child, ''''giving birth to another problem.

.......... and that is ..........

P2... If we click on any non-draggable child suppose text, then the draggable parent does not move. ...AND... if we click on the tri-line menu-button then it gets dragged instead of its draggable parent... Jsbin for P2...

$.fn.on_swipe = function(o) {

    var te = {};

    this.each(function(){

        var mainElem = $(this);

        $(document).on('mousedown', function(e) {

          e.preventDefault();

            te.target = $(e.target).closest('.'+ mainElem[0].className);
            te.bX = e.pageX;
            te.lastX = te.target.position().left;

            $(this).on('mousemove', function(e) {

                te.eX = e.pageX;
                te.posX = te.lastX + ( -1 * (te.bX - te.eX));
                o.moving(te.target, te.posX);

            }).on('mouseup', function(e) {
                te = {};
                $(this).unbind('mousemove');
                $(this).unbind('mouseup');
            });
        });
    });
};

$('.parent').on_swipe( { moving: function(target, posX) { 
        target.css( 'left' , posX + 'px'); 
    } });

$('.child').on_swipe( { moving: function(target, posX) { 
        target.css( 'left' , posX + 'px'); 
    } });

Thank you :)


Solution

  • Solved your P1... and P2.. problem

    1) Changed your "mousedown" click from document to the actual element its initialized on.

    2) added "stopPropagation()" for not to drag the parent when the child is dragged

    3) removed the "mouseup" event from the initialized element and added it to the document

    updated jsbin P1

    Let me know if you have any other concerns

    Updates: Added as per @kanudo request in the comment jsbin

    Updates: Final correct ..JSBIN..