简体   繁体   中英

Dynamically added draggable object not working the first time

I am adding the draggable functionality to an element on a particular user event(hold event). Drag functionality is not working the first time.

    Hammer(element).on("hold",function(event){
        console.log("hold");
        $(element).draggable({
                helper: "clone",
                cursorAt: { left: 5, top: -5 },
                cursor: "move",
                stop: function() {
                        $(element).draggable("destroy");
                }
        });
    });

In the above code snippet, the hold event triggers the draggable functionality but it only works when I release the hold and try it the next time. How can make the drag initiate on hold itself rather than the next time?

EDIT:

Added a sample code in jsbin .

This works for me:

$('.pic').draggable({
    revert: 'invalid',
    start: function(event, ui) {

    },
    stop: function(event, ui) {
        $(this).removeClass('dragging');
    }
});

$('body').hammer().on('hold', '.container li', function() {
    $('.pic', this).addClass('dragging');
});

$('body').hammer().on('dragstart', '.container li .pic', function(e) {
    if (!$(this).hasClass('dragging')) {
        e.preventDefault();
    }

});

How about using a delay on the draggable instead of the hold Hammer event?

 $(element).draggable({
                helper: "clone",
                cursorAt: { left: 5, top: -5 },
                cursor: "move",
                stop: function() {
                        $(element).draggable("destroy");
                },
   start: function() {
     console.log("start");
   },
                delay:300
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM