JQuery losing draggable ability on ajax returned data

Wondering if someone can help, basically I have two div containers, both droppable. Container 1 has an ajax populated list of images and each image can be dragged from Container 1 to Container 2 and back again. Problem is that it only works on a static coded image but loses the draggable ability when using dynamic content from ajax (the images appear inside Container 1 so the ajax part is working). If anyone can suggest a possible solution as I am really scratching my head with this. Thank you.

<script>

$(document).ready(function(){

var currentParent;

        $(".image").resizable({
            containment: "parent"
        }).draggable({
            revert: 'invalid',
            start: function(){
                currentParent = $(this).parent().attr('id');
            }
        });

    $('#container2').droppable({
        accept:'.image',
        drop: function(event,ui){
            if (currentParent != $(this).attr('id')){
              $(ui.draggable).appendTo($(this)).removeAttr('style');
              alert("Dropped into workspace");
            }
        }
    });

    $('#container1').droppable({
        accept:'.image',
        drop: function(event,ui){
            if (currentParent != $(this).attr('id')){
              $(ui.draggable).appendTo($(this)).removeAttr('style');
              alert("Put back into menu");
            }
        }
    });

     $.ajax({  
      url: 'images/retrieve_images.php',    
      data: 'page_id='+ encodeURIComponent(page_id),
      dataType: 'json',
      success: function(data) {

        $.each(data, function(i, val) {
            $.each(val, function(k, v) {
                $("<div class='image'><img width='auto' height='100%' src='article_images/"+v.image_name+"'/></div>").appendTo("#container1");
            });
        });

        }

    });

});

</script>

If I run a static image it works perfect:

<div id="container1">
    <div class="image"><img width="auto" height="100%" src="article_images/c5cfe4711ec60b5a676ae386702a8051.png"/></div>
</div>

<div id="container2"></div>

Answers 1

  • Add draggable to each item in the ajax success call as below

     $.ajax({  
      url: 'images/retrieve_images.php',    
      data: 'page_id='+ encodeURIComponent(page_id),
      dataType: 'json',
      success: function(data) {
    
        $.each(data, function(i, val) {
            $.each(val, function(k, v) {
                $("<div class='image'><img width='auto' height='100%' src='article_images/"+v.image_name+"'/></div>")
               .draggable({
                            revert: 'invalid',
                            start: function(){
                                currentParent = $(this).parent().attr('id');
                            }
               }).appendTo("#container1");
            });
        });
    
        }
    
    });
    

Related Articles