3

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.

fuyushimoya
  • 9,715
  • 3
  • 27
  • 34
basagabi
  • 4,900
  • 6
  • 38
  • 84

2 Answers2

2

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

Guruprasad J Rao
  • 29,410
  • 14
  • 101
  • 200
1

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/

Rohit Kumar
  • 1,948
  • 1
  • 11
  • 16