Megan Crane
Megan Crane

Reputation: 81

Draggable divs not working if created by Ajax

I'm using jQuery and Ajax to load a bunch of divs into a scrollable div ("letterHolder"):

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>

<script type="text/javascript">
$.ajax({
  url: "myphpscript.php",
  dataType: "json",   
  success: function(result) {
    $(".letterHolder").html(result['letter_array']);
  }
});
</script>
</head>

<body>

<div class="letterHolder">
</div>

</body>
</html>

The PHP script retrieves a list of filenames from the database and loads them into letterHolder, so it ends up looking like this:

<div class="letterHolder">
  <div class="drag_letter">file1</div>
  <div class="drag_letter">file2</div>
  <div class="drag_letter">file3</div>
  etc.
</div>

Now, I want to make those filename divs draggable, but this is not working:

$(".drag_letter").draggable({
 cursor: 'move',
 revert: true,
 helper: 'clone'   
});

It doesn't work if I put the draggable code into the page header, nor does it work if I put the code at the end of the page.

This was working fine before I tried creating the divs using Ajax.

Upvotes: 1

Views: 377

Answers (2)

James T
James T

Reputation: 823

I assume the reason this was working before you were using AJAX, but is not working with AJAX, is because you are calling draggable() with a selector for elements which are not yet in the DOM. If you call draggable() on the elements after receiving the AJAX result and appending the elements to the DOM it should work.

Upvotes: 2

Mahmoud.Eskandari
Mahmoud.Eskandari

Reputation: 1478

  1. Using jQuery or java script append() function for adding DOM into an element instead of html()
  2. add draggable after appending elements

you should send file names Like file1... file2... as a Json array From server

and rewrite this:

<script type="text/javascript">
$.ajax({
    url: "myphpscript.php",
    dataType: "json",
    success: function(result) {
        $.each(result,function(k,v){
            $(".letterHolder").append($('<div></div>').html(v).addClass('drag_letter').draggable({
                cursor: 'move',
                revert: true,
                helper: 'clone'
            }));
        });
    }
});
</script>

Upvotes: 0

Related Questions