javascriptjqueryhtmldraggablejquery-draggable

Draggabilly not adding event to newly added element


I'm using desandro draggabilly and I'm having a problem when inserting a new element. It seems that the event is not firing on the new element that was added.

Here's a jsfiddle.

Here's the code as well.

HTML

<div class="box draggable">1</div>

CSS

.box {
    width: 200px;
    height: 200px;
    border: 1px solid red;
    display: block;
}

JQUERY

$(document).ready(function () {
    $.bridget('draggabilly', Draggabilly);
    var $draggable = $('.draggable').draggabilly({
        axis: 'x'
    });
    $draggable.on('dragEnd', function(e, p) {
        $(this).parent().prepend('<div class="box draggable">2</div>');
        $(this).prev().addClass('draggable')
        $(this).remove();
    }); 
});

On the code below when I dragged div 1, on dragEnd it will insert div 2 that has a class of draggable then remove div 1. The problem here is that div 2 is not being draggable even though it has a class of draggable.


Solution

  • You need to re-initialize it after prepending since it is added to DOM dynamically and event draggabilly will not be attached to it. So below will fix the issue:

    $draggable.on('dragEnd', function(e, p) {
            $(this).parent().prepend('<div class="box draggable">2</div>');
            $('.draggable').draggabilly({
                axis: 'x'
            }); //re-initialize again
            $(this).remove();
    });
    

    DEMO


    UPDATE

    Now if you want to call dragend event to the element you add and keep on incrementing the number on dragend just keep a global variable say i and increment it everytime as below:

    var i=1; //global variable
    $(document).ready(function () {
        $.bridget('draggabilly', Draggabilly);
        $('.draggable').draggabilly({
            axis: 'x'
        });
    
        $(document).on('dragEnd','.draggable', function(e, p) {
            i++; //increment it
            $(this).parent().prepend('<div class="box draggable">'+i+'</div>'); 
            //display text as i
            $('.draggable').draggabilly({
                axis: 'x'
            });
            $(this).remove();//remove previous one
        });    
    });
    

    Updated demo