basagabi
basagabi

Reputation: 5064

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.

Upvotes: 3

Views: 756

Answers (2)

Guruprasad J Rao
Guruprasad J Rao

Reputation: 29683

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

Upvotes: 2

Rohit Kumar
Rohit Kumar

Reputation: 1958

You have to initialize every time on creation of your div and bind event then something as below -

$(document).ready(function () {
    $.bridget('draggabilly', Draggabilly);
    var $draggable = $('.draggable').draggabilly({
        axis: 'x'
    });

    $draggable.on('dragEnd', callback);    

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

LIVE http://jsfiddle.net/mailmerohit5/L9kgeu3f/

Upvotes: 1

Related Questions